How to send files using Hapi

This tutorial is compatible with Hapi v17.8.1

The Inert plugin provides a wide range of functionality to work with files in routes in Hapi.

First of all you need to install the Inert module to your app using NPM or Yarn and register it before your server will start.
You can install it in terminal using the next commands:

The example of simple app:

To send a file in the Hapi there is a method “res.file()”. The first argument its the path to file, the second argument to pass an options. To send a file in Hapi as an attachment we need to pass the “mode: ‘attachment'” in options object:

Server will send this “image.png” as an attachment and user will receive it to “Downloads” folder in browser. An example of app:

To show this “image.png” in browser we can just call the “res.file” method without “options” argument:

If we want to override the filename we can use the “filename” property of “options”:

For example, to send the pre-compressed version of the file, we can use the “lookupCompressed” property of “options”:

 

If you liked this, please help spread the word by hitting the recommend button below. Thanks!

Tags:,