简体   繁体   English

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

[英]Sending files in Reactjs Dropzone using multipart/form-data

I am working on an React application using a Dropzone npm package, which allows users to select multiple files. 我正在使用Dropzone npm软件包在React应用程序上工作,该软件包允许用户选择多个文件。 I would need to send these files as a multipart/form-data to my web service. 我需要将这些文件作为多部分/表单数据发送到我的Web服务。

I don't have Form to post the data, I am using the an Ajax post request to send files to my WCF service. 我没有Form来发布数据,我正在使用Ajax发布请求将文件发送到WCF服务。

I have configured the WCF to receive files as stream and I can successfully send files via PostMan as form-data in the body. 我已将WCF配置为以流形式接收文件,并且可以通过PostMan作为正文中的表单数据成功发送文件。 But just trying to figure out how I can send my Dropzone files as multipart/form-data in the react app. 但是只是想弄清楚如何在react应用程序中将我的Dropzone文件作为multipart / form-data发送。

Any input would be appreciated. 任何输入将不胜感激。

I don't have Form to post the data 我没有表格来发布数据

Why not? 为什么不? As shown in the docs here you need to create a basic form like: 由于在文档显示在这里 ,你需要创建一个基本形式,如:

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

In case you create Dropzone programmatically , that should already be present. 如果您以编程方式创建Dropzone ,则应该已经存在。

Having that, sending the Files via Ajax is easy, since all you need to do is: 有了它,通过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) {
  //...
});

as shown here . 如图所示这里 Not using a <form> cannot work, since you do not have a <input type="file" /> to give the user the opportunity to select files. 不使用<form>无效,因为您没有<input type="file" />来为用户提供选择文件的机会。 Not taking advantage of using FormData is possible, but since that is complicated and error-prone, the FormData API was introduced. 不能利用FormData优势,但是由于这很复杂且容易出错,因此引入了FormData API

That said, all you need to do is add event listener(s) to the dropzone object and do what is need to be done. 就是说,您要做的就是将事件侦听器添加到dropzone对象,然后执行需要做的事情。

The simplest form to perform an React Integratio is to use componentDidMount() and componentWillUnmount() lifecycle methods to create and destroy the dropzone object. 执行React Integratio的最简单形式是使用componentDidMount()componentWillUnmount()生命周期方法来创建和销毁dropzone对象。 The needed form can be created within the render() method or, when used programmatically, with the callback of a ref . 可以在render()方法中创建所需的表单,或者在以编程方式使用ref的回调时创建所需的表单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM