Multer Express:每个请求都有不同的文件夹

Multer Express:每个请求都有不同的文件夹,express,blob,multer,Express,Blob,Multer,我正在使用Multer和Express通过Ajax上传我放在blob中的图像列表。我可以在服务器端接收并保存这些图像。问题是,我需要相同Ajax请求的所有图像都位于同一文件夹中。我需要一个文件夹。每个文件夹都有随机的uuid名称 问题是每个图像都位于不同的文件夹中。也许问题是因为我发送的图像是一团?你有办法解决这个问题吗?非常感谢,以下是我对multer的配置: var storage = multer.diskStorage({ destination: function (req, fi

我正在使用Multer和Express通过Ajax上传我放在blob中的图像列表。我可以在服务器端接收并保存这些图像。问题是,我需要相同Ajax请求的所有图像都位于同一文件夹中。我需要一个文件夹。每个文件夹都有随机的uuid名称

问题是每个图像都位于不同的文件夹中。也许问题是因为我发送的图像是一团?你有办法解决这个问题吗?非常感谢,以下是我对multer的配置:

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    let path = './public/images/' + uuidv4() + '/'; //a different folder for each request
    file.path = path;
    fs.mkdirSync(path);
    cb(null, path);
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '.' + mime.extension(file.mimetype));
  }
})
let upload = multer({ storage: storage });

问题在于,请求的每个映像都会运行
destination
函数,每次都会创建不同的UUID,从而为每个映像创建一个新文件夹

您需要事先将UUID存储在
req
中,以便可以在
目标
函数中使用它。这将为每个请求创建一个唯一的目录

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    let path = './public/images/' + req.imagesFolder + '/';
    file.path = path;
    fs.mkdirSync(path);
    cb(null, path);
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '.' + mime.extension(file.mimetype));
  }
})
const upload = multer({ storage: storage });
并且,在使用中间件时:

const preuploadMiddleware = (req, res, next) => {
  req.imagesFolder = uuidv4();
  next();
};

app.post('/images', preuploadMiddleware, upload, (req res, next) => {
  // ...
});

问题在于,请求的每个映像都会运行
destination
函数,每次都会创建不同的UUID,从而为每个映像创建一个新文件夹

您需要事先将UUID存储在
req
中,以便可以在
目标
函数中使用它。这将为每个请求创建一个唯一的目录

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    let path = './public/images/' + req.imagesFolder + '/';
    file.path = path;
    fs.mkdirSync(path);
    cb(null, path);
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '.' + mime.extension(file.mimetype));
  }
})
const upload = multer({ storage: storage });
并且,在使用中间件时:

const preuploadMiddleware = (req, res, next) => {
  req.imagesFolder = uuidv4();
  next();
};

app.post('/images', preuploadMiddleware, upload, (req res, next) => {
  // ...
});

非常感谢你的回答:)效果很好。起初它不起作用,事实上,如果我在app.post函数中放了一个break,它就不会被击中。原因是,在multer.diskStorage.Destination中,对于第二个文件,它试图创建一个已经存在的文件夹,因此在未调用app.post的情况下失败。。。所以我只需要替换:fs.mkdirSync(path);通过if(!fs.existsSync(path)){fs.mkdirSync(path);}非常感谢您的回答:)它工作得很好。起初它不起作用,事实上,如果我在app.post函数中放了一个break,它就不会被击中。原因是,在multer.diskStorage.Destination中,对于第二个文件,它试图创建一个已经存在的文件夹,因此在未调用app.post的情况下失败。。。所以我只需要替换:fs.mkdirSync(path);如果(!fs.existsSync(path)){fs.mkdirSync(path);}