【发布时间】:2017-02-27 00:47:46
【问题描述】:
第一个文件成功通过后,我无法上传第二个文件。使用这条路线...
var multer = require('multer');
var upload = multer({dest: 'base-images/'});
var type = upload.single('file');
app.post('/admin/upload', type, function(req, res) {
//Get the temporary directory/file name
var tmp_path = req.file.path;
console.log(tmp_path); //'base-images/1d7608bb0b570c7fcf669315c6f31401'
//Create a new filename based on time
var now = new Date();
var timeID = Number(now);
var newName = timeID + ".jpg";
console.log(newName); //'1476740040280.jpg'
//Convert the random Multer name to my newName
fs.rename(tmp_path, 'base-images/'+newName, function (err) {
if (err) throw err;
fs.stat('base-images/'+newName, function (err, stats) {
if (err) throw err;
console.log('stats: ' + JSON.stringify(stats));
res.send("Done"); //Works the first time, not on subsequent ones.
//stats {"dev":16777218,"mode":33188,"nlink":1,"uid":502,"gid":20,"rdev":0,"blksize":4096,"ino":19058190,"size":101269,"blocks":200,"atime":"2016-10-17T21:33:22.000Z","mtime":"2016-10-17T21:33:22.000Z","ctime":"2016-10-17T21:33:22.000Z","birthtime":"2016-10-17T21:33:22.000Z"}
});
});
});
因此,当图像第一次通过时,它会按预期工作。如果我选择另一个图像并通过它发送,我会得到一个Error: Unexpected field,然后大约两分钟后,该原始图像的第二个版本会显示为newName 的新值。然后一分钟后,该原始图像的另一个副本出现了另一个版本的newName。似乎在第三次之后就停止了。
我的目标是能够上传图片,多张就好了,并将它们的名称设置为服务器处理它们的时间戳。
更新 1:尝试使用 multer.diskstorage()
我已经重写了它,就像下面提到的那样尝试合并磁盘存储。
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'base-images/');
},
filename: function (req, file, cb) {
var now = new Date();
var timeID = Number(now);
var newName = timeID + ".jpg";
cb(null, newName);
}
});
var upload = multer({ storage: storage }).single('file');
app.post('/admin/upload', function(req, res) {
upload(req, res, function(err) {
if (err) {
console.log('Error Occurred');
console.log(err);
return;
}
console.log(req.file);
res.send('Your File Uploaded');
console.log('Photo Uploaded');
})
});
这样写会发生三件事。
首先,初始文件上传按预期进行。
其次,在不刷新 .html 的情况下,尝试另一个文件上传会抛出 Error Occurred 并带有以下日志...
{ [Error: Unexpected field]
code: 'LIMIT_UNEXPECTED_FILE',
field: 'file',
storageErrors: [] }
第三次,不刷新,第三次尝试抛出......
fs.js:975
binding.unlink(pathModule._makeLong(path), req);
^
TypeError: path must be a string
要求我能够一次上传多个文件,而无需刷新页面。
【问题讨论】:
-
/admin/upload 路由有响应??
-
抱歉。更新了原帖。
标签: node.js express upload fs multer