简体   繁体   中英

Image upload to Imgur API via JS Fetch API is canceled by browser

I wrote a small application on Codepen to upload to a specific Imgur album using Javascript's Fetch API. The application is failing to upload, and I'm not sure why since I'm not actually getting a response from the server. The browser appears to be canceling the request rather than sending it off.

Chrome开发者工具网络标签页请求已取消

Chrome开发者工具要求详细信息

Here's my code:

const form = document.querySelector('form');
form.addEventListener('submit', event => {
  const fileInput = event.target.querySelector('input');
  const imageFile = fileInput.files[0];

  const formData = new FormData();
  formData.append('image', imageFile);
  formData.append('album', 'EVGILvAjGfArJFI');

  fetch('https://api.imgur.com/3/image', {
    method: 'POST',
    headers: new Headers({
      'Content-Type': 'multipart/form-data',
      Authorization: 'Client-ID 90ef1830bd083ba',
    }),
    body: formData
  }).then(response => {
    if (response.ok) {
      alert('Image uploaded to album');       
    }
  }).catch(error => {
    console.error(JSON.stringify(error));
    alert('Upload failed: ' + error);
  });
});

I'm not sure if I need to be reading the file or if I can pass the file object directly into the form data. I've seen examples of both methods online, and I've tried both with the same result. I notice dev tools doesn't seem to show the image data in the request body. Not sure if that means it isn't being sent or if Chrome is just not displaying it since it wouldn't be human-readable anyway. I've tried the request with CORS mode on and off.

Any guidance on what I'm doing wrong here?

For FormData, you don't actually need the Content-Type header. The browser automatically adds that for you when have a FormData type in the body. I think that's because that header needs some additional info (when the browser automatically handles it, it looks like multipart/form-data; boundary=----WebKitFormBoundaryvAmR7mCXOyHiPIH5 on my machine).

Here's the updated pen that looks like it's working: https://codepen.io/ccnokes/pen/wyBYOd

Also, because you're submitting that data via a <form> but handling the request via fetch , you need to tell the <form> not to do a full page navigation change to POST the form (which cancels the fetch). So I added event.preventDefault() in the submit handler on that form.

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