使用Fetch和FormData API上载多个文件

时间:2017-11-12 20:34:28

标签: javascript ruby-on-rails ecmascript-6 multipartform-data react-dropzone

我正在尝试使用原生的FetchFormData API一次将多个文件上传到服务器,但我无法让我的生活让它发挥作用。这就是我所拥有的:

// 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,      
  });
}

但我的Rails服务器收到的是:

Parameters: {"files"=>#
<ActionDispatch::Http::UploadedFile:0x00007feb347becc0 @tempfile=#
<Tempfile:/var/folders/kl/y1jrp7zs55sbx075jjjl3p280000gn/T/RackMultipart201
71112-6486-1ftkufy.mp4>, @original_filename="SampleVideo_1280x720_5mb.mp4",
 @content_type="video/mp4", @headers="Content-Disposition: form-data; 
name=\"files\"; filename=\"SampleVideo_1280x720_5mb.mp4\"\r\nContent-Type:
 video/mp4\r\n">}

换句话说,看起来files实际上只是一个文件。但是docs for FormData say that append should append multiple files

那么出了什么问题?

1 个答案:

答案 0 :(得分:5)

解决方案是将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, }); }

json.Marshaler