Uploading multiple files with Fetch and FormData APIs

前端 未结 1 1287
渐次进展
渐次进展 2021-02-04 08:05

I\'m trying to use the native Fetch and FormData APIs to upload multiple files at once to the server but I can\'t for the life of me get it to work. Here\'s what I\'ve got:

相关标签:
1条回答
  • 2021-02-04 08:56

    The solution was to change files to files[]:

    // acceptedFiles are File objects coming from `react-dropzone`.
    function handleSubmit(acceptedFiles) {
      const data = new FormData();
    
      for (const file of acceptedFiles) {
        data.append('files[]', file, file.name);
      }
    
      return fetch('https://example.com/api/upload', {
        method: 'POST',
        body: data,      
      });
    }
    
    0 讨论(0)
提交回复
热议问题