使用 multipart/form-data 在 Reactjs Dropzone 中发送文件

Sending files in Reactjs Dropzone using multipart/form-data

我正在使用 Dropzone npm 包开发 React 应用程序,它允许用户 select 多个文件。我需要将这些文件作为 multipart/form-data 发送到我的网络服务。

我没有 post 数据的表单,我正在使用 Ajax post 请求将文件发送到我的 WCF 服务。

我已将 WCF 配置为以流形式接收文件,并且我可以通过 PostMan 将文件作为正文中的表单数据成功发送。但只是想弄清楚如何在 React 应用程序中将我的 Dropzone 文件作为 multipart/form-data 发送。

如有任何意见,我们将不胜感激。

I don't have Form to post the data

为什么不呢?如文档中所示 here 您需要创建一个基本表单,例如:

<form action="/file-upload"
  class="dropzone"
  id="my-awesome-dropzone">
  <input type="file" name="file" />
</form>

如果您创建 Dropzone programmatically,它应该已经存在。

有了它,通过 Ajax 发送文件就很容易了,因为您需要做的就是:

//create a FormData Object
//that will care about all
//the mimetypes etc
const fd = new FormData(document.getElementById('my-awesome-dropzone'));

fetch(<url>, {
  method: 'POST',
  body: fd
}).then(function (response) {
  //...
});

如图所示. Not using a <form> cannot work, since you do not have a <input type="file" /> to give the user the opportunity to select files. Not taking advantage of using FormData is possible, but since that is complicated and error-prone, the FormData API被引入。

也就是说,您需要做的就是将 event listener(s) 添加到 dropzone 对象并执行需要完成的操作。

执行 React Integratio 的最简单形式是使用 componentDidMount()componentWillUnmount() 生命周期方法来创建和销毁 dropzone 对象。可以在 render() 方法中创建所需的表单,或者在以编程方式使用时,通过 ref.

的回调创建