首页 > 解决方案 > 在 Axios vue.js 中使用 multipart/form-data 发布请求发送数组数据

问题描述

我正在使用 Axios 从 vue.js 项目发送一个发布请求,它包含一个文件上传,这需要我使用 FormData,我找到了一个很好的答案,可以帮助我使用 FormData:

const getFormData = object => Object.keys(object).reduce((formData, key) => {
     formData.append(key, object[key]);
     return formData;
}, new FormData());

对于标题:headers: { 'Content-Type': 'multipart/form-data'}.

POST 调用如下所示:

axios.post("http://127.0.0.1:8000/api/document/",
      getFormData(this.documentData),
      {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      .then(response => {
        console.log("Successfully uploaded: ", response.data)
      })
      .catch(err => {
        console.log("error occured: ", err)
      })

这是我要发送的数据:

documentData: {
      name: '',
      file: '',
      version: '',
      company: '',
      author: '',
      category: []
    }

发送具有单个类别 id 的数据时,它工作正常,但是当我发送多个类别 id 时,显示以下错误:

"category": [
    "Incorrect type. Expected pk value, received str."
]

我怎么解决这个问题?

标签: javascriptvue.jsaxios

解决方案


假设您的服务器端进程期望数组类型有多个重复的字段名称,您将需要这样的东西

const getFormData = object => Object.entries(object).reduce((fd, [ key, val ]) => {
  if (Array.isArray(val)) {
    val.forEach(v => fd.append(key, v))
  } else {
    fd.append(key, val)
  }
  return fd
}, new FormData());

一些服务器端进程(例如 PHP)要求集合类型字段包含[]后缀。如果这就是您正在使用的,请更改此行

val.forEach(v => fd.append(`${key}[]`, v))

此外,FormData从浏览器发送时,请勿手动设置Content-type标题。您的浏览器将为您执行此操作,包括所需的边界令牌

axios.post("http://127.0.0.1:8000/api/document/", getFormData(this.documentData))
  .then(response => {
    console.log("Successfully uploaded: ", response.data)
  })
  .catch(err => {
    console.error("error occurred: ", err)
  })


推荐阅读