首页 > 解决方案 > 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'; 
}

标签: node.jsimage-uploadingmulter

解决方案


我已经确认它适用于以下代码:

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);,如果它按预期工作,我建议您检查此方法。(我只能怀疑那部分代码。)


推荐阅读