I used the express framework and tried to use multer middleware for uploading. It turned out to be the most basic upload, which is
var upload = multer({ dest: 'uploads/' }), but I found that this upload The files are all 16-bit random strings without suffix names. My requirement is to standardize file naming, so I used multer.diskStorage to perform more operations on the files. Here is my code:
`var express = require('express');
var router = express.Router();
var multer = require('multer');
//Set the save path
//var upload = multer({ dest: 'uploads/' })
/ GET home page. /
router.get('/', function(req, res, next) {
res.render('index', { title: ' Express' });
});
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/uploads');
},
filename: function (req, file, cb) {
cb(null, file.fieldname+"-"+Date.now());
}
});
var upload = multer({ storage: storage });
router.post('/upload', upload.single('image')), function(req, res, next){
var image=req.file.path;
res.send('index', { title : 'Express' ,image:image});
}
module.exports = router;
`
I feel this should be the most basic demo, but it just reports a 500 error. The error is as follows:
POST /upload 500 16.841 ms - 1278
Error: Failed to lookup view "error" in views directory "D:\wx_bandu\views"
at EventEmitter.render (D:\wx_bandu\node_modules\._express@4.15.3@express\lib\application.js:580:17)
at ServerResponse.render (D:\wx_bandu\node_modules\._express@4.15.3@express\lib\response.js:971:7)
at D:\wx_bandu\app.js:45:7
at Layer.handle_error (D:\wx_bandu\node_modules\._express@4.15.3@express\lib\router\layer.js:71:5)
at trim_prefix (D:\wx_bandu\node_modules\._express@4.15.3@express\lib\router\index.js:315:13)
at D:\wx_bandu\node_modules\._express@4.15.3@express\lib\router\index.js:284:7
at Function.process_params (D:\wx_bandu\node_modules\._express@4.15.3@express\lib\router\index.js:335:12)
at next (D:\wx_bandu\node_modules\._express@4.15.3@express\lib\router\index.js:275:10)
at Layer.handle_error (D:\wx_bandu\node_modules\._express@4.15.3@express\lib\router\layer.js:67:12)
at trim_prefix (D:\wx_bandu\node_modules\._express@4.15.3@express\lib\router\index.js:315:13)
I read a lot of information on the Internet, and also on github, but I feel like I just can’t find the reason, please give me some guidance
500 is a server error, line 45 of app.js is wrong,
res.send('index', { title : 'Express' ,image:image});
, are you going to transfer the file to the browser?After working on it for a long time, the default error.jade cannot be displayed because I used the pug template and later changed it. The error is clear at a glance. The path set by the destination starts from the root directory of the hard disk. For example, I wrote /uploads, The storage path is D://uploads. Because there is no such folder, it keeps reporting errors. Just modify it and it will be fine