Search code examples
javascriptreactjsreact-nativedropzone.jsreact-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. I would need to send these files as a multipart/form-data to my web service.

I don't have Form to post the data, I am using the an Ajax post request to send files to my WCF service.

I have configured the WCF to receive files as stream and I can successfully send files via PostMan as form-data in the body. But just trying to figure out how I can send my Dropzone files as multipart/form-data in the react app.

Any input would be appreciated.


Solution

  • 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.

    Having that, sending the Files via Ajax is easy, since all you need to do is:

    //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. Not taking advantage of using FormData is possible, but since that is complicated and error-prone, the FormData API was introduced.

    That said, all you need to do is add event listener(s) to the dropzone object and do what is need to be done.

    The simplest form to perform an React Integratio is to use componentDidMount() and componentWillUnmount() lifecycle methods to create and destroy the dropzone object. The needed form can be created within the render() method or, when used programmatically, with the callback of a ref.