Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

We want to send an image file as multipart/form to the backend, we try to use html form to get 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 backend is "nested exception is org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found".

After reading this, we tried to set boundary to headers in fetch:

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, the error in backend is: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause

Do we add the multipart boundary right? Where should it be? Maybe we are wrong at first because we don't get the multipart/form-data. How can we get it correctly?

like image 985
Taro Yehai Avatar asked Jan 12 '17 10:01

Taro Yehai


People also ask

How send multipart data in react JS?

We can send form data with the FormData constructor. We can pass that straight into the Axios post method. We have a file input, where we set the file input to the file that's submitted in the onChange method.

How do I upload a multipart file to react JS?

Multipart File Upload with React Hook Form​ export default App; To manage our form and its elements, we defined the register and handleSubmit methods from the react hook form. Now, let's upload the file selected in our onSubmit method to our server by placing it in the formData.


2 Answers

We just try 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!");     }); 
like image 157
Taro Yehai Avatar answered Sep 22 '22 12:09

Taro Yehai


Here is my solution for image upload with preview through axios.

import React, { Component } from 'react'; import axios from "axios"; 

React Component Class:

class FileUpload extends Component {      // API Endpoints     custom_file_upload_url = `YOUR_API_ENDPOINT_SHOULD_GOES_HERE`;       constructor(props) {         super(props);         this.state = {             image_file: null,             image_preview: '',         }     }      // Image Preview Handler     handleImagePreview = (e) => {         let image_as_base64 = URL.createObjectURL(e.target.files[0])         let image_as_files = e.target.files[0];          this.setState({             image_preview: image_as_base64,             image_file: image_as_files,         })     }      // Image/File Submit Handler     handleSubmitFile = () => {          if (this.state.image_file !== null){              let formData = new FormData();             formData.append('customFile', this.state.image_file);             // the image field name should be similar to your api endpoint field name             // in my case here the field name is customFile              axios.post(                 this.custom_file_upload_url,                 formData,                 {                     headers: {                         "Authorization": "YOUR_API_AUTHORIZATION_KEY_SHOULD_GOES_HERE_IF_HAVE",                         "Content-type": "multipart/form-data",                     },                                     }             )             .then(res => {                 console.log(`Success` + res.data);             })             .catch(err => {                 console.log(err);             })         }     }       // render from here     render() {          return (             <div>                 {/* image preview */}                 <img src={this.state.image_preview} alt="image preview"/>                  {/* image input field */}                 <input                     type="file"                     onChange={this.handleImagePreview}                 />                 <label>Upload file</label>                 <input type="submit" onClick={this.handleSubmitFile} value="Submit"/>             </div>         );     } }  export default FileUpload; 
like image 22
Fatema Tuz Zuhora Avatar answered Sep 20 '22 12:09

Fatema Tuz Zuhora