File upload is a very common feature on a website but there is only few resources teaching you how to do it using the
I found a very useful and easy-to-use module called Multer.
In this article I will tell about how to upload files to server using and multer package from npm, filter upload files by extension and validate file by check magic numbers. But what if we want to allow to upload only image files?
Since multer does not provide file data (we need bitmap in this case) as a solution we can check the magic numbers after uploading the file to the server and if it does not match then delete this file from filesystem.
File name to be saved can be specify in the function "filename".
In line 12, we create a upload function with Multer.
Also, the two events on File Upload Start and on File Upload Complete never seem to be triggered as I don't get anything logged in my console.
I am using two separate files for the server and the routing: /** * Dependencies */ var express = require('express'); var path = require('path'); var logger = require('morgan'); var cookie Parser = require('cookie-parser'); var body Parser = require('body-parser'); /** * Importation of routes */ var routes = require('./routes/index'); var recog = require('./routes/recog'); /** * Express */ var app = express(); app.use(logger('dev')); app.use(body Parser.json()); app.use(body Parser.urlencoded()); app.use(cookie Parser()); app.use(express.static(path.join(__dirname, 'public'))); // pour contrer les erreurs de cross domain app.use(function (req, res, next) ); /** * Routes */ app.use('/', routes); app.use('/recog', recog); module.exports = app; /** * Requirements */ var express = require('express'); var router = express.
You can find the documentation on their Git Hub page but I’ll demo how to build a simple api to handle file upload. In this function, you can determine the destination of the file and the name of it.