使用Fetch和FormData API上传多个文件 [英] Uploading multiple files with Fetch and FormData APIs

查看:597
本文介绍了使用Fetch和FormData API上传多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用本机获取 FormData API可以一次将多个文件上传到服务器,但是我无法为我的生命工作.这就是我所拥有的:

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:

// 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服务器收到的是:

But what my Rails server receives is this:

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实际上只是一个文件.但是FormData文档说,附加应该附加多个文件.

In other words, it looks like files is actually just one file. But the docs for FormData say that append should append multiple files.

那怎么了?

推荐答案

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

这篇关于使用Fetch和FormData API上传多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆