Upload Files In NodeJS Express (Very Simple Example)

Welcome to a quick tutorial on how to upload files in NodeJS Express. So you may have just started with Express, and wondering how to handle file uploads? Well, it really isn’t too difficult, here is a very simple example – Read on!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TABLE OF CONTENTS

Download & Notes Express Upload Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

  • Unzip into your project folder.
  • Run npm i express express-fileupload.
  • Run node 2-server.js and access http://localhost in your browser.
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

EXPRESS FILE UPLOAD

All right, let us now get into the example of handling a file upload in the NodeJS Express framework.

 

PART 1) REQUIRED MODULES

First, we are going to need the Express and Express file upload modules. Run npm i express express-filupload in your project folder.

 

PART 2) EXPRESS SERVER

2-server.js
// (A) INITIALIZE
// (A1) LOAD REQUIRED MODULES
const path = require("path"),
      express = require("express"),
      fileUpload = require("express-fileupload");

// (A2) EXPRESS + MIDDLEWARE
// https://www.npmjs.com/package/express-fileupload
const app = express();
app.use(fileUpload());
 
// (B) EXPRESS HTTP
// (B1) UPLOAD PAGE
app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname, "/3-upload.html"));
});
 
// (B3) MANAGE UPLOAD
app.post("/upload", (req, res) => {
  // (B3-1) UPLOADED FILE & DESTINATION
  let upfile = req.files.upfile,
      updest = __dirname + "/" + upfile.name;
 
  // (B3-2) MOVE UPLOADED FILE
  upfile.mv(updest, (err) => {
    if (err) { return res.status(500).send(err); }
    res.send("File uploaded!");
  });
});
 
// (C) GO!
app.listen(80);

Yes, that is all we require on the NodeJS script.

  1. Self-explanatory. We are just loading the required modules, and setting Express to use the file upload module.
  2. Define / to serve the HTML file upload form, and /upload to handle the file upload itself.
  3. Don’t think this needs any explanation.

 

 

PART 3) HTML UPLOAD FORM

3-upload.html
<form action="http://localhost/upload" method="POST" enctype="multipart/form-data">
  <input type="file" name="upfile" required/>
  <input type="submit" value="Upload!"/>
</form>

Finally, this should not require any explanation either – It’s just your “regular HTML upload form”.

 

USEFUL BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

RESTRICTING FILE TYPES

<input type="file" name="upfile" accept="image/*" required/>

In the HTML, we can easily impose an accept="FILE TYPE" restriction.

// ALLOWED FILE TYPES
const allowed = ["image/jpeg", "image/png", "image/gif"];
 
// SAVE UPLOAD ONLY IF ALLOWED FILE TYPE
if (console.log(allowed.includes(upfile.mimetype))) {
  upfile.mv(...);
} else { res.send("NOPE"); }

But the HTML file type restrictions are not reliable – Anyone who knows how to work with the developer’s console can easily mess with it. So, it’s still safer to implement checks on the server side.

 

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published.