第一次成功完成后,我无法上传第二个文件。使用这条路线......
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()
我重写了它,就像尝试合并下面提到的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
要求是我能够一次一个地上传多个文件,而无需刷新页面。
答案 0 :(得分:0)
尝试使用此代替fs.rename(我还没有测试过这段代码,可能会出现一些错误)
var storage = multer.diskStorage({
destination: '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 })