node.js - NodeJS,使用 Multer 上传多张照片,但最后一张照片覆盖了所有其他照片
问题描述
我正在使用 NodeJS 和 multer 在特定文件夹中上传 1 张或多张照片。当我上传 1 张照片时,它工作正常。当我尝试上传 2 张或更多照片时,它们会上传到特定文件夹中,但最后一张照片会覆盖所有其他照片(它们保持正确的名称,但照片内容只是被覆盖)。
var storage = multer.diskStorage({
destination: function (request, file, callback) {
//tag and path are 2 function to set the name and path directory
//tag example = ['IV190', '207401_SITRASB', '7738_IV19001G10101']
var tag = file.originalname.split('-');
//path example = "C:/progetti/sios4_nodejs/SIOS4_siosnew/Documentale/
//Commesse/207401_SITRASB/Opere/IV190/foto"
var path = commons.getImagesPath(tag[0], tag[1], false);
mkdirp.sync(path)
return callback(null, path);
},
filename: function (request, file, callback) {
//Example filename: 7738_IV19001G111.jpg
var tag = file.originalname.substr(file.originalname.lastIndexOf('-') + 1);
return callback(null, tag)
}
});
var upload = multer({storage: storage});
router.post('/:inspectiongroup_id/reportingpictures/upload',
upload.array('files'), function (req, res) {
return models.sequelize.transaction(function (t) {
//....few inserts in dB, nothing related to multer and upload
res.json({status: 'ok', message: 'Pictures uploaded'});
});
});
我不知道为什么最后一张会覆盖其他图片……有什么线索吗?
提前致谢。
编辑:这是 commons.getImagesPath(tag[0], tag[1], false),其中
tag[0] = 'IV190' //building_code in the function
tag[1] = '207401_SITRASB' //ori_code in the function
config.images_root_folder = "C:/progetti/sios4_nodejs/SIOS4_siosnew/Documentale/Commesse"
//false
commons.getImagesPath = function(building_code,ori_code, thumb){
if(thumb)
return config.images_root_folder +'/'+ori_code+'/Opere/'+building_code+'/Thumbnail';
else
return config.images_root_folder +'/'+ori_code+'/Opere/'+building_code+'/foto';
}
解决方案
我已经确认它适用于以下代码:
const mkdirp = require("mkdirp");
const path = require("path");
const app = require("express")();
const multer = require("multer");
var storage = multer.diskStorage({
destination: function(_req, file, done) {
const tag = file.originalname.split("-");
const dir = path.join(__dirname, ...tag.slice(0, tag.length-1));
mkdirp.sync(dir);
return done(null, dir);
},
filename: function(_req, file, done) {
const filename = file.originalname.substr(file.originalname.lastIndexOf("-") + 1);
return done(null, filename);
}
});
const upload = multer({ storage });
app.post("/images", upload.array("images"), function(req, res) {
res.json({ status: "ok", message: "Pictures uploaded" });
});
app.listen("3000", () => console.log("Listening on :3000"));
您的代码和上面的代码之间的唯一区别是commons.getImagesPath(tag[0], tag[1], false);
,如果它按预期工作,我建议您检查此方法。(我只能怀疑那部分代码。)
推荐阅读
- xamarin - 如何让我的应用程序在首次打开时提示“希望向您发送通知”消息?
- powershell - 使用 power shell 脚本将证书导入证书存储不起作用但手动工作
- machine-learning - Keras 验证准确度为 0,并且在整个训练过程中保持不变
- r - 将样式指南放在 R 包中的位置
- powershell - 在 Powershell 脚本中使用正斜杠查找字符串中的子字符串
- java - InterruptedIOException 是否将线程的 Interrupted 标志设置为 true?
- php - db 获取和查看文件的日志消息
- angular - Angular 和 ng 选择。选定项目的确认
- ios - UIScreenEdgePanGestureRecognizer
- javascript - JS/jQuery 承诺