Does fetch support multiple file upload natively?

前端 未结 2 1513
终归单人心
终归单人心 2021-01-07 12:05

Summary

I am trying to set my FormData properly using javascript.

I need to be able to upload jpg/png, but I might need to upload

相关标签:
2条回答
  • 2021-01-07 12:31

    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) {
      data.append('files',file,file.name)
    }
    
    fetch('http://localhost:8080/api/upload/multi', {
      method: 'POST',
      body: data
    })
    
    0 讨论(0)
  • 2021-01-07 12:41

    The issue with your code is in the lineformData.append('files', input.files); Instead of that, you should upload each file running a loop with unique keys, like this

    const fileList = document.querySelector('input[type="file"]').files;
        for(var i=0;i<fileList.length;i++) {
        formData.append('file'+i, fileList.item(i));    
    }
    

    I have created a simple error fiddle here with your code. You can check its' submitted post data here, where you can see that no file has been uploaded.

    At the bottom of the page you can find

    .

    I have corrected the fiddle here with the fix. You can check its'post data from the server, where it shows the details of the two files that I uploaded.

    0 讨论(0)
提交回复
热议问题