我用的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,因為沒有這個資料夾,所以它一直報錯,只要把它修改一下就好了