This article describes you how to upload files in Node.js without using multipart/form-data. The related resources are as follows.
The procedure is as follows:
- Preparing for coding
- Coding
- Check
Open a terminal and execute the following command.
mkdir nodejs-upload-non-multipart
cd nodejs-upload-non-multipart
npm init -y
touch client.js index.html server.js
Open index.html in your editor and enter the following content.
Open client.js in your editor and enter the following content.
The points are as follows:
- If you need to send some parameters, use a query string.
- Specify the file in the body of the fetch function call.
Open server.js in your editor and enter the following content.
The points are as follows:
- Get the request body as a buffer.
- Write the file using the fsPromises.writeFile function. Create a directory using the fsPromises.mkdir function before writing the file.
Execute the following command to start the server.
node server.js
Go to http://localhost:3000/ in your browser.
Select the file and then click the submit button.
Confirm that the selected file has been uploaded.
I think the advantage of the method described in this article is that it consumes less memory than the method using multipart/form-data.
If the server sends the received file to cloud storage such as Amazon S3, you don't need to write the file to local storage. If the file you are uploading is large, it is better to use the fs.createWriteStream function instead of getting the request body as a buffer.
If you have any questions, please feel free to comment. Thank you for reading!