Home > database >  How to upload a file into a S3 bucket using a presigned url with Nuxt.js and Axios?
How to upload a file into a S3 bucket using a presigned url with Nuxt.js and Axios?

Time:11-05

I would like to use Axios on my Nuxt.js website to upload a file into a S3 bucket. I already managed the part to get the presigned URL. When I try to use the presigned URL with Postman, everything's working fine but when I try it with Axios I get this error: Uncaught (in promise) ReferenceError: Access is not defined.

Here is my code:

<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>

As it's working with Postman, I guess the error come from my Axios configuration.

CodePudding user response:

You're specifying your content type header wrong.

Replace:

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

With:

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