You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Nuxt.js中通过Axios使用预签名URL上传文件到S3存储桶

问题排查与修复

你遇到的报错及上传失败问题由以下3个代码错误导致:

  • 配置请求头时,Content-Type作为对象键时未加引号,JavaScript会将其识别为未定义的变量,直接触发ReferenceError报错
  • S3预签名PUT上传无需使用multipart/form-data格式,也不需要将文件包裹在files字段中,直接传递文件二进制流作为请求体即可,错误的请求体格式会导致S3签名校验失败
  • Vue实例不存在setState方法,该方法为React框架独有,Vue中直接给响应式属性赋值即可
修正后的完整代码
<template>
  <v-file-input label="选择要上传的文件" accept="image/*" v-model="myFile">
    上传到S3的文件
  </v-file-input>
</template>

<script>
export default {
  data() {
    return {
      myFile: null,
      ApiGatewayUrl: "https://xxxxxx.execute-api.eu-central-1.amazonaws.com/",
      statusCode: 0
    }
  },
  methods: {
    async uploadFile() {
      try {
        // 获取预签名URL
        const presignResponse = await this.$axios.get(this.ApiGatewayUrl, {
          headers: {
            Authorization: this.$auth.strategy.token.get()
          }
        })
        // 直接PUT文件到预签名地址
        const uploadResponse = await this.$axios.put(presignResponse.data, this.myFile, {
          headers: {
            // 和生成预签名URL时约定的Content-Type保持一致即可,这里直接取文件本身的类型
            'Content-Type': this.myFile.type
          }
        })
        // 直接给Vue响应式属性赋值
        this.statusCode = uploadResponse.status
      } catch (err) {
        console.error('上传失败', err)
      }
    }
  }
}
</script>

内容的提问来源于stack exchange,提问作者Sébastien Serre

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 22:24:05