【问题标题】:How to post a file(pdf,doc) in axios service along with JSON data如何在 axios 服务中发布文件(pdf,doc)以及 JSON 数据
【发布时间】:2018-06-09 01:43:30
【问题描述】:

我想在 axios 服务中发送 PDF/Docs 文件以及其他 JSON 数据。 我参考了 (Ajax post a file from a form with Axios) 但它只发送没有任何 JSON 数据的文件。

 field_value: {}, // here it shows empty object,but it should show File Object
 field_type: "file_upload", 
 is_file_upload: true

}

当我在发送请求之前控制台对象时,它会在 FormData() 中向我显示一个文件对象,但在发布请求中看到它时它会显示空括号。

【问题讨论】:

  • 我会将文件转换为 base64 并将其与其他 JSON 数据一起附加。
  • 感谢 Madhu,如​​果我将文件转换为 base64,那么我如何识别服务器端是 PDF 还是 Image 或 Docx
  • 将文件或图像转换为base64时,第一部分以文件类型data:application/pdf;base64, .....开头。使用它您可以识别文件类型。

标签: json file laravel-5 vuejs2 axios


【解决方案1】:

你可以这样做:

//HTML    
<input type="file" @change="onFileChanged" :multiple="multiple" :accept="accept" />

然后你的javascript代码来处理文件输入:

onFileChanged(event) {
  var files = event.target.files || event.dataTransfer.files;
  if (!files.length) {
    return;
  }

  var formData = new FormData();

  // Add the File object to the formdata
  if (this.multiple) {
    formData.append("files", files);
  } else {
    formData.append("file", files[0]);
  }

  // Add your data...
  formData.append("data", myData);
}

uploadDocument(formData) {
  return Axios.post('/api/documents', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  });
}

使用从文件输入类型获得的formData发送到后端。

然后你可以这样做:

uploadDocument(formData).then((response) => {
  console.log('data sent');
})  

希望对你有帮助。

【讨论】:

  • 感谢 Sambor,但您的解决方案仅在请求中发送文件,它没有任何其他 JSON 数据要发送。
  • 检查行 // 添加你的数据... formData.append("data", myData);
猜你喜欢
  • 2017-04-30
  • 2020-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-17
  • 1970-01-01
  • 2019-09-10
  • 2018-06-10
相关资源
最近更新 更多