简体   繁体   English

如何使用 NodeJs Multer 上传 2 个图像不同的 2 个文件夹?

[英]How to upload 2 image different 2 folder with NodeJs Multer?

I have a problem and stuck with how to upload 2 image different 2 folder with NodeJs Multer?我遇到问题并坚持如何使用 NodeJs Multer 上传 2 个图像不同的 2 个文件夹? I use s3 AWS service to upload my image to bucket我使用 s3 AWS 服务将我的图像上传到存储桶

My route code:我的路线代码:

const { s3Service } = require('../../services')

module.exports = (req, res, next) => {
  const controller = new Controller()
  const router = new express.Router()

  router.route('/createEvent').post(
    s3Service.upload.single('image'),
    controller.createEvent
  )

My multer code:我的多重代码:

const multer = require('multer')
const AWS = require('aws-sdk')
const fs = require('fs')
const s3 = new AWS.S3({
  accessKeyId: process.env.BUCKET_ACCESSKEYID,
  secretAccessKey: process.env.BUCKET_SECRETACCESSKEY,
  endpoint: process.env.BUCKET_ENDPOINT
})

const storage = multer.diskStorage({
  filename: function (req, file, cb) {
    let filename = file.originalname
    filename = filename.replace(/ /g, '-')
    cb(null, 'event' + '-' + Date.now() + '-' + filename)
  }
})

const upload = multer({
  storage
})

const uploadToBucket = (fileContent, folderName, fileName, fileType) => {
  const params = {
    Bucket: process.env.BUCKET_NAME,
    Key: folderName + '/' + fileName,
    Body: fs.createReadStream(fileContent),
    ContentType: fileType,
    ACL: 'public-read'
  }

  s3.upload(params, (err, data) => {
    if (err) {
      console.log(err)
    }
    if (data) {
      fs.unlinkSync(fileContent)
      const url = data.Location
      console.log(url)

      return url
    }
  })
}

And my controller create function:我的控制器创建函数:

      const path = req.file.path
      s3Service.uploadToBucket(path, 'events', req.file.filename, req.file.mimetype)
      payload.image = {
        name: req.file.filename,
        url: process.env.BUCKET_EVENTSTORAGE + req.file.filename,
        type: req.file.mimetype,
        size: req.file.size
      }

      const data = await Event.create(payload)

I have already have upload 1 image, but i need to upload another image called certificate only if eventCertified have value true .我已经上传了 1 张图片,但只有当 eventCertified 的值为true时,我才需要上传另一张名为certificate的图片。 I stuck and never try that before.我卡住了,以前从未尝试过。

With multer, normally to handle multiple files you just have to change使用 multer,通常只需更改即可处理多个文件

from

const upload = multer({
  storage
})

to

const max_files_limit=2 // whatever that meets your need
const upload = multer({storage}).array('images',max_files_limit); // 'images', the first parameter, should be the name of your fields in the HTML form,etc

// In your code it should be like this I suppose
s3Service.upload.array('images',max_files_limit)

You can find multiple references here and there for examples.您可以在这里那里找到多个参考示例。

After the multer middleware upload your files, the req object will have the files property on it.在 multer 中间件上传你的文件后,req 对象将具有 files 属性。

You can access the mutiple files simply like that您可以像那样访问多个文件

const files = req.files // simply use req.files to retreive all your files
const events_promises=[]
for(let i=0;i<req.files.length;i++){
      s3Service.uploadToBucket(files[i].path, 'events', files[i].filename, files[i].mimetype)
      payload.image = {
        name: files[i].filename,
        url: process.env.BUCKET_EVENTSTORAGE + files[i].filename,
        type: files[i].mimetype,
        size: files[i].size
      }
      events.push(Event.create(payload)) // put all your promises / async in an array
      }
      
let events_result=Promise.all(events); // wait for all your promises to finish at once
await events_result // or events_result.then("something else");

I tried to follow your code logic, but I didn't test it or mock it, so sorry if there is some typo or unexpected error.我试图遵循您的代码逻辑,但我没有对其进行测试或模拟,如果有错字或意外错误,我们深表歉意。 In my example I put all the promises Event.create() in an array, to await on all the promises at once, if one Event create fail, the code in the example won't catch it propely.在我的示例中,我将所有承诺 Event.create() 放在一个数组中,一次等待所有承诺,如果一个事件创建失败,示例中的代码将无法正确捕获它。

Hope it helps希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM