1. Run cmd in the directory first, execute the following command
NPM install multer;
2, the new upload.js under the router
Let Express = require (' Express ');
Let router = Express. Router ();
Let FS = require (' FS ');
Let Multer = require (' Multer ');
//Use hard disk storage mode to set the path and file name for the received files
Let Storage1 = Multer.diskstorage ({
Destination:function (req, file, CB) {
Save path to output after receiving file (if not present)
CB (NULL, ' public/images/');//Save normal Picture
},
Filename:function (req, file, CB) {
//Set the save file name to timestamp + file original name, such as 151342376785-123.jpg
CB (NULL, file.originalname);
}
});
Let Storage2 = Multer.diskstorage ({
Destination:function (req, file, CB) {
//The save path of the output after receiving the file (if it does not exist, you need to create it) br> CB (NULL, ' public/images/avatar/'); Save Avatar
},
Filename:function (req, file, CB) {
//Set Save file name to timestamp + file original name, e.g. 151342376785-123.jpg
CB (NULL, file.originalname);
}
});
//Create folder
Let CreateFolder = function (folder) {
try{
//test the user right of the file or directory specified by path, we use to detect if the file exists
//AS The file path does not exist and will throw an error "No such file or directory"
Fs.accesssync (folder);
}catch (e) {
///folder does not exist to create the file directory in a synchronized manner.
Fs.mkdirsync (folder);
}
};
General picture
Let UploadFolder1 = './public/images/';
CreateFolder (UploadFolder1);
Avatar
Let UploadFolder2 = './public/images/avatar ';
CreateFolder (UPLOADFOLDER2);
Create a Multer object
Let Upload1 = Multer ({storage:storage1});
Let upload2 = Multer ({storage:storage2});
/* POST upload listing. */
Router.post ('/addlanguage ', upload1.single (' file '), function (req, res, next) {
let file = Req.file;
Return data to front end after receiving file success
Res.json ({res_code: ' 0 '});
});
Router.post ('/addavatar ', upload2.single (' file '), function (req, res, next) {
let file = Req.file;
Return data to front end after receiving file success
Res.json ({res_code: ' 0 '});
});
Export module (introduced in app.js)
Module.exports = router;
3, finally introduced in the App.js use
var upload = require ('./routes/upload ');
App.use ('/upload ', upload);
Nodejs Implement image upload