React.js how to send multipart / form-data to server

We want to send the image file as multipart / form to the backend, we are trying to use the html form to receive the file and send the file as formData, here are the codes

export default class Task extends React.Component { uploadAction() { var data = new FormData(); var imagedata = document.querySelector('input[type="file"]').files[0]; data.append("data", imagedata); fetch("http://localhost:8910/taskCreationController/createStoryTask", { mode: 'no-cors', method: "POST", headers: { "Content-Type": "multipart/form-data" "Accept": "application/json", "type": "formData" }, body: data }).then(function (res) { if (res.ok) { alert("Perfect! "); } else if (res.status == 401) { alert("Oops! "); } }, function (e) { alert("Error submitting form!"); }); } render() { return ( <form encType="multipart/form-data" action=""> <input type="file" name="fileName" defaultValue="fileName"></input> <input type="button" value="upload" onClick={this.uploadAction.bind(this)}></input> </form> ) } } 

The error in the backend is a "nested exception." org.springframework.web.multipart.MultipartException: failed to parse multi-hearted servlet request, nested exception - java.io.IOException: org.apache.tomcat.util.http.fileupload. FileUploadException: The request was rejected because a multiline border was not found. "

After reading this, we tried to set the border for the headers in the sample:

 fetch("http://localhost:8910/taskCreationController/createStoryTask", { mode: 'no-cors', method: "POST", headers: { "Content-Type": "multipart/form-data; boundary=AaB03x" + "--AaB03x" + "Content-Disposition: file" + "Content-Type: png" + "Content-Transfer-Encoding: binary" + "...data... " + "--AaB03x--", "Accept": "application/json", "type": "formData" }, body: data }).then(function (res) { if (res.ok) { alert("Perfect! "); } else if (res.status == 401) { alert("Oops! "); } }, function (e) { alert("Error submitting form!"); }); } 

This time an error in the backend: Servlet.service () for the servlet [dispatcherServlet] in the context with the path [] threw an exception [Error processing request; the nested exception is java.lang.NullPointerException] with the root cause.

Will we add a polyhedral border to the right? Where should it be? Perhaps we are mistaken at first, because we are not receiving data about multipart / form-data. How can we get it right?

+13
source share
4 answers

We are just trying to remove our headers and it works!

 fetch("http://localhost:8910/taskCreationController/createStoryTask", { mode: 'no-cors', method: "POST", body: data }).then(function (res) { if (res.ok) { alert("Perfect! "); } else if (res.status == 401) { alert("Oops! "); } }, function (e) { alert("Error submitting form!"); }); 
+9
source

The file is also available in case of:

 e.target.files[0] 

(eliminates the need for document.querySelector('input[type="file"]').files[0]; )

 uploadAction(e) { const data = new FormData(); const imagedata = e.target.files[0]; data.append('inputname', imagedata); ... 

Note: Use console.log(data.get('inputname')) for debugging, console.log(data) will not display the added data.

+2
source

Respond to file uploads

 import { Component } from 'react'; class Upload extends Component { constructor() { super(); this.state = { image: '', } } handleFileChange = e => { this.setState({ [e.target.name]: e.target.files[0], }) } handleSubmit = async e => { e.preventDefault(); const formData = new FormData(); for (let name in this.state) { formData.append(name, this.state[name]); } await fetch('/api/upload', { method: 'POST', body: formData, }); alert('done'); } render() { return ( <form onSubmit={this.handleSubmit}> <input name="image" type="file" onChange={this.handleFileChange}> </input> <input type="submit"></input> </form> ) } } export default Upload; 
0
source

To send multipart/formdata you need to avoid contentType since the browser automatically assigns a boundary and Content-Type .

In your case, using fetch , even if you avoid Content-Type , it sets the default value to text/plain . So try with jQuery ajax . which removes contentType if we set it to false.

This is working code.

 var data = new FormData(); var imagedata = document.querySelector('input[type="file"]').files[0]; data.append("data", imagedata); $.ajax({ method: "POST", url: fullUrl, data: data, dataType: 'json', cache: false, processData: false, contentType: false }).done((data) => { //resolve(data); }).fail((err) => { //console.log("errorrr for file upload", err); //reject(err); }); 
-1
source

Source: https://habr.com/ru/post/1262688/


All Articles