使用' multer' ,我这样请求图像文件。
此文件存储在'上传'我设置的文件夹。 我的代码如下:
var multer = require('multer')
var upload = multer({dest:'./uploads/'});
//var upload = multer({ storage: storage });
var app = express();
app.use(app.router);
app.post('/upload', upload.single('puzzle'), function (req, res, next) {
console.log(req.file);
});
但我想将我的文件名设置为' abc.png'不是' abc'
我阅读了文档,我发现的是
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 });
所以修改后的代码如下:
var multer = require('multer')
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/uploads');
},
filename: function (req, file, cb) {
cb(file.filename+'.png', file);
}
});
var upload = multer({ storage: storage });
var app = express();
app.use(app.router);
app.post('/upload', upload.single('puzzle'), function (req, res, next) {
console.log(req.file);
});
但在这种情况下,会发生错误并说出错误:ENOENT,open' / uploads / puzzle-1449496743377' ,不像上面的图片......
我怎么解决这个问题?
我确信很多像我这样的新手开发者会因为不友善的文档而遇到麻烦......
答案 0 :(得分:1)
var fs = require('fs');
var multer = require('multer')
//var uploader = multer({dest:'./uploads/'});
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads/')
},
filename: function (req, file, cb) {
crypto.pseudoRandomBytes(16, function (err, raw) {
cb(null, raw.toString('hex') + Date.now() + '.png');
});
}
});
var upload = multer({ storage: storage });
var app = express();
app.use(app.router);
app.post('/upload', upload.single('puzzle'), function (req, res, next) {
console.log(req.file);
});
解决了,谢谢大家,谢谢你
答案 1 :(得分:0)
我认为您的问题在于目标目录的定义。起点'。'不见了。 尝试使用此代码:
destination: function (req, file, cb) {
cb(null, './uploads/');
},