How to upload file in Hapi

In this tutorial, we will learn how to handle file uploading in Hapi. We will discover the next cases: binary data and stream.

Introduction

In this tutorial, we will use the following Hapi server:

We will change the logic of POST /submit route to support file uploading.

Uploading binary file data

Let’s set the correct payload format to allow us binary upload:

If we send the binary data, we will get the next data on server:

  • path – the temporary path to uploaded file
  • bytes – the size of file

Then we can make any actions with the file using the path to this file.

Uploading data or file as stream

If we send the data as stream, we need to change payload to the following:

Suppose, we have the following HTML form and sends these data to our POST /submit  endpoint:

Now, in route handler we can get our image and imageName data in payload object:

The req.payload.image will contains the Readable Stream object. We can get more information about file name and headers using hapi object in req.payload.image. We should see something similar to the next object:

If you want to save readable stream to file, I recommend you to follow this tutorial.

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

Tags:,