首页 > 解决方案 > 如何使用带有 Nuxt.js 和 Axios 的预签名 URL 将文件上传到 S3 存储桶?

问题描述

我想在我的 Nuxt.js 网站上使用 Axios 将文件上传到 S3 存储桶中。我已经管理了获取预签名 URL 的部分。当我尝试将预签名 URL 与 Postman 一起使用时,一切正常,但是当我与 Axios 一起尝试时,我收到此错误:Uncaught (in promise) ReferenceError: Access is not defined.

这是我的代码:

<template>
  <v-file-input label="Select your file to upload" accept="image/*" v-model="myFile">
    File to upload to S3
  </v-file-input>
</template>

<script>
export default {
  data() {
    return {
      myFile: null,
      ApiGatewayUrl: "https://xxxxxx.execute-api.eu-central-1.amazonaws.com/"
    }
  },
  methods: {
    uploadFile() {
      // get the pre-signed URL
      this.$axios.get(this.ApiGatewayUrl, {
        headers: {
          Authorization: this.$auth.strategy.token.get()
        }
      }).then((response) => {
      
        // now do a PUT request to the pre-signed URL
        this.$axios.put(response.data, {
          files: this.myFile
        }, {
          headers: {
            [Content-Type]: 'multipart/form-data'
          }
        }).then((response) => {
          this.setState({
            statusCode: response.status,
          })
        })
      })
    }
  }
}
</script>

由于它与 Postman 一起工作,我猜错误来自我的 Axios 配置。

标签: javascriptamazon-s3axiosnuxt.js

解决方案


您指定的内容类型标题错误。

代替:

headers: {
    [Content-Type]: 'multipart/form-data'
}

和:

headers: {
    "Content-Type": "multipart/form-data"
}

推荐阅读