X

Node.js

Uploading Files using Fetch fs.rename & FormData

June 29, 2021

/*

Uploading Files using fetch, fs.rename() & FormData

*/

Last week, we uploaded files using Multer & Express. This week we're going to add to that with fetch, fs.rename() & the FormData class. We'll be using the same html file. We're going to create an app.js file, grab our form & put a submit event listener on it. Inside the submit event, run preventDefault() to stop the form from submitting.

Next, we're going to use a post fetch, this is we're we use FormData. In the body of the fetch post request, we're going to say new FormData(form). This is going to grab our html form & make it into a set of key/value pairs. The best thing about this is the form will be in multipart/form-data.

<code-div></code-div>

/*

Renaming Uploaded Files with fs.rename()

*/

We'll be adding onto the index.js file we used last time. In the fetch post route, we're going to run forEach() on the files we're uploading. Inside each loop, we'll call fs.rename() on the file. This method takes 2 arguments & a callback. The first argument is the old path, the second is the new path. The req.files object comes with a destination property that gives us the path of the file saved. We'll also use the req.files filename propery which will tell us the name that multer gave it when it was uploading. Finally, we'll use the req.files original name to give it the name you have on your computer. After the forEach loop, we'll send a res.json message back to the client saying "All files have been uploaded".

<code-div></code-div>

/*

The Final Result

*/

The final result is here.

About the Author

Christopher Howard

Chris is a Javascript developer with a minor in UI design. He values programming in vanilla code. Fill out the form below to contact him.