Hi everyone ,
In this tutorial i will show how to upload images using ExpressJs server , using multer.
To start with let's created a brand new ExpressJs application.this is fairly easy so i won't focus on it much. if you want more you can check out my hello world in ExpressJs tutorial. And i'll use that same project from where we left off.
Build your first ExpressJs server from scratch.
Rajitha Gunathilake γ» Dec 1 '19
after setting up your expressjs app . we have to install multer for file upload handling.so you know what to do right.
npm i multer
But what is multer anyway ? well....
multer is a Node.js middleware used to handle multipart form data, mostly used to upload files in Nodejs.So what it will do is grab the files we send from the client side as multipart form data and process them to a format so we can easily interact with them(store in disk , upload to another server etc).
keep in mind that multer will only process multipart formdata
OK now we know what multer is let's move on ...
There are two options we can have in multer to store received files.
- disk storage - writes the file to directly to our file system
- memory storage - temporarily saves our file in memory(RAM)
these 2 options have different use cases , but you can use it either way.
let's start with file upload to disk.
first of all import multer library
const multer = require("multer");
after that we need to create an object with the options we need when file storage. This will include where we need to save the file in our filesystem and also what is the filename.
you can specify any filename you want. for example if you need to keep track of the file upload time you can attach the timestamp to the file name by using Date.now()
js date object . but keep in mind to append the original file format at the end of it.
var storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, "./"); //here we specify the destination. in this case i specified the current directory
},
filename: function(req, file, cb) {
console.log(file); //log the file object info in console
cb(null, file.originalname);//here we specify the file saving name. in this case.
//i specified the original file name .you can modify this name to anything you want
}
});
after that we need to specify the file which storage engine we are going to use.
var uploadDisk = multer({ storage: storage });
then create a brand new route called /fileuploaddisk
. this route cannot be GET
route . so i'll use a POST
route . PUT
can also be used.
this route will first go through our multer middleware to process form data we are sending.then that middleware will grab our data and then it will save it in our local filesystem.
uploadDisk.single("image")
is used to identify which form field contains our multipart data.here we specify image because in the frontend name of our multipart formdata field is image
. you could use any name, but one should tally with the other.
in uploadDisk.single("image")
, single
stands for what type of multipart formdata we are expecting. single
tells that we only send one file in this request.there are also other options like array
so we can send multiple images.
for simplicity i'll go with single
file.
app.post("/fileuploaddisk", uploadDisk.single("image"), (req, res) => {
console.log(" file disk uploaded");
res.send("file disk upload success");
});
now the only thing left is to spin up our server. and also since we don't have a frontend , we can a api request builder to act as our front end.here i will be using Postman
now send a POST
request to http://localhost:5000/fileuploaddisk
keep in mind to select body for your post request and use form-data
in the request body options. then add a key with image
since we specified our upload as image
in backend. and also make sure you selected file. then the value will open a window to select your file.
and we successfully uploaded a file .
disk storage app.js
now let's move on to file upload via memory storage.
it is also very similar to disk storage but we won't specify any options like before.
keep in mind that since memory storage temporary store the files in our memory. it will use a lot of memory if we upload large files , or large amounts of small files. but normal file sizes usage won't be affected .
since we already imported multer. But to write the file from memory to we need another module called 'fs' which is a module in Node.js for filesystem operations.'fs' is a builtin module in Node.js so we don't have to install anything.
const fs = require("fs");
next specify the storage engine.in this case we will specify memory storage.
var storage = multer.memoryStorage();
var uploadMem = multer({ storage: storage });
next we will create a new POST
route /fileuploadmem
.
reasons for single
and image
is same as the above example.But unlike disk storage memory storage middleware will not write file directly to the file system. it will process our request and then manipulates the req
object and appends a new file
object to it. file
object have an attribute called buffer
which contains our file in a buffer. so write that to an object we need the fs
module. fs.writeFileSync
method will write that buffer to our file system.
app.post("/fileuploadmem", uploadMem.single("image"), (req, res) => {
console.log(req.file);
fs.writeFileSync('./'+req.file.originalname , req.file.buffer)
console.log(" file mem uploaded");
res.send("file mem upload success");
});
now let's test our memory upload with postman by sending a
POST
request to http://localhost:5000/fileuploadmem
.
keep in mind to select body for your post request and use form-data
in the request body options. then add a key with image
since we specified our upload as image
in backend. and also make sure you selected file. then the value will open a window to select your file.
and we get our success message.
memory storage app.js
Top comments (3)
if my requirement is to upload 1gb file into google coud via post method should i use diskstorage or memorystorage? please help me
i think it is better to use services GCP storage for larger files , because it is more reliable and also versatile .
Well written. But how to upload large size files like say, multiple 100 MB files in a single post? Currently, it only allows files with combine size smaller than 50 MB. Any idea?