javascript - 如何使用JS提取API上传文件?

original title: "javascript - How do I upload a file with the JS fetch API?"


I am still trying to wrap my head around it.

I can have the user select the file (or even multiple) with the file input:

    <label>Select file to upload</label>
    <input type="file">
  <button type="submit">Convert</button>

And I can catch the submit event using <fill in your event handler here>. But once I do, how do I send the file using fetch?

fetch('/files', {
  method: 'post',
  // what goes here? What is the "body" for this? content-type header?
}).then(/* whatever */);

我仍在努力把它缠住。我可以让用户使用文件输入来选择文件(甚至多个): <form><div> <label>选择要上传的文件</label>并...


  • Translate

    This is a basic example with comments. The upload function is what you are looking for:

    // Select your input type file and store it in a variable
    const input = document.getElementById('fileinput');
    // This will upload the file after having read it
    const upload = (file) => {
      fetch('', { // Your POST endpoint
        method: 'POST',
        headers: {
          // Content-Type may need to be completely **omitted**
          // or you may need something
          "Content-Type": "You will perhaps need to define a content-type here"
        body: file // This is your file object
        response => response.json() // if the response is a JSON object
        success => console.log(success) // Handle the success response object
        error => console.log(error) // Handle the error response object
    // Event handler executed when a file is selected
    const onSelectFile = () => upload(input.files[0]);
    // Add a listener on your input
    // It will be triggered when a file will be selected
    input.addEventListener('change', onSelectFile, false);

  • Translate

    I've done it like this:

    var input = document.querySelector('input[type="file"]')
    var data = new FormData()
    data.append('file', input.files[0])
    data.append('user', 'hubot')
    fetch('/avatars', {
      method: 'POST',
      body: data

  • Translate

    An important note for sending Files with Fetch API

    One needs to omit content-type header for the Fetch request. Then the browser will automatically add the Content type header including the Form Boundary which looks like

    Content-Type: multipart/form-data; boundary=—-WebKitFormBoundaryfgtsKTYLsT7PNUVD

    Form boundary is the delimiter for the form data

  • Translate

    If you want multiples file, you can use this

    var input = document.querySelector('input[type="file"]')
    var data = new FormData()
    for (const file of input.files) {
    fetch('/avatars', {
      method: 'POST',
      body: data

  • Translate

    To submit a single file, you can simply use the File object from the input's .files array directly as the value of body: in your fetch() initializer:

    const myInput = document.getElementById('my-input');
    // Later, perhaps in a form 'submit' handler or the input's 'change' handler:
    fetch('', {
      method: 'POST',
      body: myInput.files[0],

    This works because File inherits from Blob, and Blob is one of the permissible BodyInit types defined in the Fetch Standard.

  • Translate

    Jumping off from Alex Montoya's approach for multiple file input elements

    const inputFiles = document.querySelectorAll('input[type="file"]');
    const formData = new FormData();
    for (const file of inputFiles) {
        formData.append(, file.files[0]);
    fetch(url, {
        method: 'POST',
        body: formData })

  • Translate

    The problem for me was that I was using a response.blob() to populate the form data. Apparently you can't do that at least with react native so I ended up using

    data.append('fileData', {
      uri : pickerResponse.uri,
      type: pickerResponse.type,
      name: pickerResponse.fileName

    Fetch seems to recognize that format and send the file where the uri is pointing.