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

Vue多图上传报错:Failed to execute 'append' on 'FormData'

解决Vue多图片上传的FormData Blob类型错误

问题根源

你遇到的Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'错误,核心原因有两个:

  1. 调用FormData.append()时,第二个参数传入了未定义的photos[i](组件data里的photos始终为null,从未赋值),不是有效的File/Blob对象
  2. append方法的参数传递完全错误,同时存在FileList遍历逻辑、文件名获取的问题

修正后的完整代码

<template>
  <input
    type="file"
    @change="onFileSelected"
    multiple
    ref="files"
  />
  <!-- 其他上传按钮等内容 -->
</template>

<script>
import axios from 'axios'

export default {
  data() {
    return {
      selectedFiles: null, // 改为复数更符合语义
      stockQuantity: 1,
      fileNames: [] // 存储所有选中文件的文件名,可选
    };
  },
  methods: {
    onFileSelected(event) {
      this.selectedFiles = event.target.files;
      // 修正文件名获取逻辑:FileList没有name属性,需遍历每个文件
      this.fileNames = Array.from(this.selectedFiles).map(file => file.name);
      console.log('选中的文件:', this.selectedFiles);
    },
    async onAddProduct() {
      // 先判断是否有选中文件
      if (!this.selectedFiles || this.selectedFiles.length === 0) {
        console.log('请先选择文件');
        return;
      }

      const data = new FormData();
      // 直接遍历FileList(FileList是可迭代对象,无需Object.keys)
      for (const file of this.selectedFiles) {
        // FormData.append正确用法:字段名、File对象、文件名(可选,默认用file.name)
        data.append('photos', file, file.name);
      }

      try {
        // axios会自动识别FormData并设置正确的Content-Type(包含boundary),无需手动设置
        const response = await axios.post('http://localhost:5000/api/products', data);
        console.log('上传成功:', response);
        // this.$router.push('/')
      } catch (error) {
        console.error('上传失败:', error);
      }
    }
  }
};
</script>

关键修正点

  • 变量语义优化:把selectedFile改为selectedFiles,更贴合多文件场景
  • 文件名获取修正:event.target.files是FileList对象,没有name属性,需通过遍历每个File对象获取文件名
  • FormData构建修正:
    • 直接用for...of遍历FileList,无需通过Object.keys转换
    • append方法只传递必要参数:字段名photos、当前File对象、文件名(可选)
  • 请求头优化:删除手动设置的Content-Type,axios会自动为FormData添加包含boundary的正确请求头,避免手动设置导致的错误
  • 错误处理:添加try/catch捕获上传过程中的异常,方便调试

内容的提问来源于stack exchange,提问作者xander

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 15:54:54