【问题标题】:Nuxt Upload multiple files toS3Nuxt 将多个文件上传到 S3
【发布时间】:2021-05-14 04:51:08
【问题描述】:

我试图弄清楚如何将多个文件上传到我的 S3 存储桶,但似乎无法弄清楚。我正在使用 express api 运行 Nuxt.js 应用程序。我只是在测试要上传的 1 或 2 个文件,但得到 500 响应并出现错误: 配置中缺少凭据,如果使用 AWS_CONFIG_FILE,请设置 AWS_SDK_LOAD_CONFIG=1。

我的 Vue 模板:/pages/add.vue

<template>
  <v-col cols="12">
    <h2 class="display-1 font-weight-light mb-5">Add Photos</h2>
    <v-form
      ref="uploadForm"
      v-model="valid"
      enctype="multipart/form-data"
      lazy-validation
      @submit.prevent="submitFiles"
    >
      <v-row>
        <v-col cols="12" sm="6">
          <v-file-input
            v-model="photos"
            :counter="30"
            :rules="uploadRules"
            accept="image/png, image/jpeg"
            show-size
            multiple
            label="Click to upload photos"
          />
        </v-col>
        <v-col cols="12" sm="6">
          <v-btn :loading="loading" color="primary" @click="submitFiles()">
            Upload
          </v-btn>
        </v-col>
      </v-row>
    </v-form>
  </v-col>
</template>

<script>
export default {
  layout: 'admin',
  data: () => ({
    photos: [],
    uploadRules: [(v) => (v && v.length <= 30) || 'No more than 30 files'],
    valid: true,
    loading: false
  }),
  methods: {
    submitFiles() {
      if (this.$refs.uploadForm.validate()) {
        this.loading = true
        const formData = new FormData()
        const Form = this

        for (let i = 0; i < this.photos.length; i++) {
          const file = this.photos[i]
          formData.append(`photos['${i}']`, file)
        }

        this.$axios
          .post('/photos/upload', formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          })
          .then((res) => {
            console.log('success')
            console.log(res)
          })
          .catch((error) => {
            console.log('fail')
            console.log(error)
          })
          .finally(() => {
            Form.loading = false
            Form.photos = []
          })
      }
    }
  }
}
</script>

我的上传文件:/utils/upload.js

const aws = require('aws-sdk')
const multer = require('multer')
const multerS3 = require('multer-s3')
const s3 = new aws.S3()

aws.config.update({
  apiVersion: '2006-03-01',
  accessKeyId: process.env.AWS_KEY,
  secretAccessKey: process.env.AWS_SECRET,
  region: process.env.AWS_REGION_APP
})

const upload = multer({
  storage: multerS3({
    s3,
    bucket: process.env.BUCKET,
    acl: 'public-read',
    metadata: (req, file, cb) => {
      cb(null, { fieldName: file.fieldname })
    },
    key: (req, file, cb) => {
      cb(null, Date.now().toString())
    }
  })
})

module.exports = upload

我的快递 api:/api/photos.js

const express = require('express')
const app = express()
const bodyParser = require('body-parser')
app.use(bodyParser.json())

const upload = require('../utils/upload')

// Upload photos
app.post('/upload', upload.array('photos', 3), (req, res) => {
    res.send('Successfully uploaded ' + req.files.length + ' files!')
})

module.exports = app

【问题讨论】:

  • 只是一个简单的问题:您是否必须通过 Express API 来上传文件,还是可以直接从浏览器上传?因为使用适用于浏览器的 aws-sdk,您可以直接在 Nuxt 应用程序中执行此操作。
  • 根据您是否需要一个安全且唯一的生成 URL,您确实需要一个后端 @yaiks
  • 这是真的@kissu!只是想知道这是否是 OP 案例

标签: amazon-s3 nuxt.js multer-s3


【解决方案1】:

我仍然不确定为什么,但是在我安装 aws-cli 来测试我的凭据之后,它起作用了。

我还更新了 add.vue 文件中的部分代码 来自:

for (let i = 0; i < this.photos.length; i++) {
   const file = this.photos[i]
   formData.append(`photos['${i}']`, file)
}

到:

for (let i = 0; i < this.photos.length; i++) {
   formData.append(`photos`, this.photos[i])
}

【讨论】:

    猜你喜欢
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-07
    • 2017-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多