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

2019-02-06 16:34发布

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?

3条回答
Juvenile、少年°
2楼-- · 2019-02-06 16:50

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!");
    });
查看更多
The star\"
3楼-- · 2019-02-06 16:55

For sending multipart/formdata, you need to avoid contentType, since the browser automatically assigns the boundary and Content-Type.

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

This is the 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);
});
查看更多
别忘想泡老子
4楼-- · 2019-02-06 17:06

The file is also available in the event:

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 appended data.

查看更多
登录 后发表回答