2

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the reply. In my react .tsx file, although there is no <form> tag being using, I am using dropzone component like this: <Dropzone onDrop={this.onDrop.bind(this)} > <p>drop files here</p> </Dropzone> and it does generate an <input type="file" /> tag upon page render. Could I use data from this input tag and use in the FormData.append() method?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.