Skip to content

File Upload with Multer

Veerpal Brar edited this page Mar 30, 2020 · 1 revision

ConnectEd uses the multer package to handle image uploads. Multer knows how to handle multi-part form data and provides a convient interface for dealing with images.

Uploading images in Client

The client can upload an image to the server easily using vanilla JavaScipt. First create an input field to upload an image from the users computer. <input type="file" id="file" ref="file"/>

You can submit the image to the server using form data

    this.file = file = this.$refs.file.files[0];
    var form = new FormData();
    form.append("profile_picture", this.file);
    axios.post("/connect/create_profile", form, {
		headers: { "Content-Type": "multipart/form-data" }
    }).then(response => {
		...
    }).catch(function(error) {
		...
    });

Handling Image Uploads in the Server

Multer acts as middleware in the Express Application. Meaning before user code is run to handle an api request, Multer will run to handle the file uploads in the request. If you look at the multer set up in server/src/app.js you will see that multer is configured to limit iamge uplaods to 2MB and stores all uploaded images in server/src/images folder with a randomly generated name.

var storage = multer.diskStorage({
	destination: function (req, file, cb) {
	    cb(null, 'src/images')
         },

        filename: function (req, file, callback) {
	    crypto.pseudoRandomBytes(16, function(err, raw) {
	    if (err) return callback(err);
		callback(null, raw.toString('hex') + path.extname(file.originalname));
	    });
	}
})

var upload = multer({ storage: storage , limits: {fileSize: 1000000 }}) //limit 1MB
require('./routes')(app, upload) 

You won't have to change this configuration and should be able to use multer directly.

To specify that a certain route will be expecting a file upload, add upload.single('param') to the route that has the file upload. Here param refers to the named parameter that contains the file.

For example, app.post('/connect/create_profile', upload.single('profile_picture'), ProfileController.register), means the /connect/create_profile request expects to be passed a image via the profile_picture parameter. Multer will run during each request made to /connect/create_profile and take the file passed from the profile_picture params and save it to the images folder.

After saving a file, Multer adds a file object to the request object that contains the files uploaded via the form. You can access the upload within the response handler by doing req.file. For example, you can get the file's name by using req.file.filename

Clone this wiki locally