我打算使用multer上传多个文件,然后将它们重命名为原始名称。以下是示例代码:
var express = require('express');
var app = express();
var fs = require("fs");
var multer = require('multer');
app.use(express.static('public'));
var upload = multer({ dest: './upload/' });
app.get('/index.html', function (req, res) {
res.sendFile(__dirname + "/" + "index.html");
})
app.post('/file_upload', upload.array('theFile', 2), function (req, res, next) {
var errorcode = 0;
for (var i = 0; i < req.files.length; i++) {
fs.rename(req.files[i].path, req.files[i].destination + req.files[i].originalname, function (err) {
errorcode = err;
}(i));
}
if (errorcode != 0) {
console.log("errorcode is " + errorcode);
res.sendStatus(500);
return;
} else {
res.json({
message: 'File uploaded successfully',
});
}
})
var server = app.listen(8089, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
我在Windows服务器上测试上面的代码。我的观察是文件可以成功上传,但fs.rename()不断返回错误&#34; 1&#34;。目标文件夹中重命名的文件总是1Kb。似乎重命名函数打算获取可能仍在上传的文件。我不确定我的理解是否正确。如果是这样,有没有办法确定文件是否已完全上传?对我的问题有任何建议吗?
答案 0 :(得分:0)
为什么不使用Multer的内置重命名功能?
改编自文档:
var storage = multer.diskStorage({
destination: '/path/to/uploads/folder',
filename: function (req, file, cb) {
// Here we specify the file name to save it as
cb(null, file.originalname);
}
})
// And we can use it for example like this:
app.post('/upload', upload.single('image'), function (req, res, next) {
// req.file is the `image` file
// req.body will hold the text fields, if there were any
})
但是,如果你采用这种方法,你应该注意几件事情:
file.originalname
类似于../../index.js
时会发生什么?将文件名转换为slug可能更好。