首页 > 解决方案 > 如何使用nodejs中的multer将多个文件上传到aws中的s3存储桶?

问题描述

下面是我编写的将单个文件上传到 AWS 中的 s3 存储桶的代码。我想知道现在如何使用下面的代码上传多个文件。为了允许上传多个文件,我需要做哪些更改?我正在尝试使用 multer,但无法弄清楚如何将其集成到下面的代码中。

     var AWS = require("aws-sdk")
    const mimeTypes = require("mimetypes")
    var errorCode = require("../util/errorCode")
    
    const awsSetup = () => {
      var wasabiEndpoint1 = new AWS.Endpoint(process.env.wasabiEndpoint)
      return new AWS.S3({
        endpoint: wasabiEndpoint1,
        accessKeyId: process.env.accessKeyId,
        secretAccessKey: process.env.secretAccessKey,
        region: process.env.region,
        httpOptions: { timeout: 180000 }
      })

}


 const fileUpload = (key, params, data, CB) => {
      const bucket = "assets.xyz.com"
      var aws_s3 = awsSetup()
    
      var mimeType = data.file.match(/[^:]\w+\/[\w-+\d.]+(?=;|,)/)[0]
      var fileType = mimeTypes.detectExtension(mimeType)
      var bufData = Buffer.from(data.file.replace(/^data:image\/\w+;base64,/, ""), "base64")
    
      if (!mimeType || !fileType || !bufData) CB(errorCode.INVALID_FILE_FORMAT, 500, null)
    
      try {
        const obj = {
          Bucket: bucket + key,
          ACL: "public-read",
          Key: params._id + `.${fileType}`,
          Body: bufData,
          ContentEncoding: "base64",
          ContentType: mimeType
        }
        aws_s3
          .headObject({ Bucket: bucket + key, Key: params._id + `.${fileType}` })
          .promise()
          .then(
            () => {
              aws_s3.putObject(obj, function (err, response) {
                if (err) CB({ message: errorCode.INTERNAL_SERVER_ERROR }, 500, null)
                else CB(null, 200, { url: `https://s3.wasabisys.com/assets.xyz.com${key}/${params._id}` + `.${fileType}` })
              })
            },
            (err) => {
              if (err.code === "NotFound") {
                aws_s3.putObject(obj, function (err, response) {
                  if (err) CB(errorCode.INTERNAL_SERVER_ERROR, 500, null)
                  else CB(null, 200, { url: `https://s3.wasabisys.com/assets.xyz.com${key}/${params._id}` + `.${fileType}` })
                })
              }
            }
          )
      } catch (err) {
        CB("CATCH ERROR in fileUpload", 500, null)
        console.log("File not Found ERROR : " + err)
      }
    }

标签: node.jsamazon-s3multer

解决方案


推荐阅读