简体   繁体   English

上传文件时,axios不允许我设置Content-Type

[英]axios won't let me set a Content-Type when uploading a file

I'm doing: 我正在做:

          return axios.request({
            headers: {
              "Content-Type": uploadFile.type // This is set to application/flac
            },
            method: "PUT",
            data: formData,
            url: respAudio.signedUploadUrl,
            timeout: 0,
            onUploadProgress: progressEvent => {
              this.uploadProgress =
                (progressEvent.loaded / progressEvent.total) * 100 - 10;
            }
          });

And for formData : 对于formData

      let formData = new FormData();
      const uploadFile = document.querySelector("#fileUploadInput").files[0];

      formData.append("file", uploadFile);

But the Request Headers show: 但是请求标头显示: 在此处输入图片说明

How can I get axios to respect the Content-Type that I set? 如何使axios尊重我设置的Content-Type

Since your formData is a FormData instance with a file in it, it doesn't surprise me that axios sets the Content-Type header to the correct value for uploading a form. 由于您的formData是其中包含文件的FormData实例,因此axiosContent-Type标头设置为用于上传表单的正确值不足为奇。

There's no need to change the Content-Type of the form data being uploaded. 无需更改要上传的表单数据的Content-Type The MIME type of the file is part of the data in the form. 文件的MIME类型是表单中数据的一部分 You'd only change it if you were include the file data itself in the PUT, not a form containing the file data. 仅当您将文件数据本身包括在PUT中而不是包含文件数据的表单中时,才需要更改它。


In a comment you said: 您在评论中说:

My server needs to know the correct MIME type of the file and all the browser is sending is multipart/form-data 我的服务器需要知道文件的正确MIME类型,并且浏览器发送的所有内容都是multipart/form-data

The browser is correct. 浏览器是正确的。 You're sending a form , not a file . 您发送的是表格 ,而不是文件 If you want to send a file, don't use FormData ; 如果要发送文件,请不要使用FormData read the file data into an ArrayBuffer and send that. 将文件数据读取到ArrayBuffer并将其发送。 Something along these lines: 遵循以下原则:

return new Promise((resolve, reject) => {
  const uploadFile = document.querySelector("#fileUploadInput").files[0];
  let reader = new FileReader();
  reader.onload = () => {
    resolve(
      axios.request({
        headers: {
          "Content-Type": uploadFile.type // This is set to application/flac
        },
        method: "PUT",
        data: reader.result,
        url: respAudio.signedUploadUrl,
        timeout: 0,
        onUploadProgress: progressEvent => {
          this.uploadProgress =
            (progressEvent.loaded / progressEvent.total) * 100 - 10;
        }
      })
    );
  };
  reader.onerror = () => {
    reject(/*...*/);
  };
  reader.readAsArrayBuffer(uploadFile)
});

That may need tweaking, but it's the general idea. 这可能需要调整,但这是总的想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM