简体   繁体   中英

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 :

      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?

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.

There's no need to change the Content-Type of the form data being uploaded. The MIME type of the file is part of the data in the form. You'd only change it if you were include the file data itself in the PUT, not a form containing the file data.


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

The browser is correct. You're sending a form , not a file . If you want to send a file, don't use FormData ; read the file data into an ArrayBuffer and send that. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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