我用的express框架,尝试用multer中间件做上传,原来是最基础的上传,就是
var upload = multer({ dest: 'uploads/' }),但是我发现这上传上去的文件都是没有后缀名的16位随机字符串,我的要求是要规范化的文件命名,所以我用了multer.diskStorage对文件进行更多的操作下面是我的代码:
`var express = require('express');
var router = express.Router();
var multer = require('multer');
//设置保存路径
//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;
`
我感觉这应该是最基本的demo了,但是就是报500错误,报错如下:
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)
我看了网上很多资料,github上也看了,感觉就是找不到原因,求大神指点迷津
500是服务器错误,app.js第45行错了,
res.send('index', { title : 'Express' ,image:image});
,你准备把文件传到浏览器?搞了半天,本身默认的error.jade展示不出来,因为我用了pug模板,后来改过来了,错误一目了然,destination设置的路径是从硬盘根目录开始的,比如我写的是/uploads,那储存的路径就是D://uploads,因为没有这个文件夹,所以它一直报错,只要把它修改一下就好了