400 (Bad Request) Error - Spring-boot File upload Using JQuery AJAX

Related searches

I am trying to upload a picture using thymeleaf ajax and spring-boot. I have used most of the post i found on stackoverflow and other forums but i does seem to work. i have add CSRF on my security configuration and also included it in the ajax upload script, but still facing the "400 (Bad Request)" error.

Exception error

017-03-01 23:50:06.893 ERROR 58753 --- [nio-8080-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is org.apache.commons.fileupload.FileUploadException: Stream closed] with root cause

java.io.IOException: Stream closed
    at org.apache.catalina.connector.InputBuffer.read(InputBuffer.java:372) ~[tomcat-embed-core-8.0.30.jar:8.0.30]
    at org.apache.catalina.connector.CoyoteInputStream.read(CoyoteInputStream.java:190) ~[tomcat-embed-core-8.0.30.jar:8.0.30]
    at java.io.FilterInputStream.read(FilterInputStream.java:133) ~[na:1.8.0_65]
    at org.apache.commons.fileupload.util.LimitedInputStream.read(LimitedInputStream.java:134) ~[commons-fileupload-1.3.2.jar:1.3.2]
    at org.apache.commons.fileupload.MultipartStream$ItemInputStream.makeAvailable(MultipartStream.java:999) ~[commons-fileupload-1.3.2.jar:1.3.2]
    at org.apache.commons.fileupload.MultipartStream$ItemInputStream.read(MultipartStream.java:903) ~[commons-fileupload-1.3.2.jar:1.3.2]
    at java.io.InputStream.read(InputStream.java:101) ~[na:1.8.0_65]
    at org.apache.commons.fileupload.util.Streams.copy(Streams.java:100) ~[commons-fileupload-1.3.2.jar:1.3.2]
    at org.apache.commons.fileupload.util.Streams.copy(Streams.java:70) ~[commons-fileupload-1.3.2.jar:1.3.2]
    at org.apache.commons.fileupload.MultipartStream.readBodyData(MultipartStream.java:593) ~[commons-fileupload-1.3.2.jar:1.3.2]


<form id="upload-file-input" th:action="@{/uploadFile}" method="post" th:object="${picture}" enctype="multipart/form-data" class="form-inline inline new-item">
        <div th:replace="common/layout :: flash"></div>
            <legend> Upload Picture</legend>
        <div class="row">
            <div class="col s12 l8">
                <div class="file-wrapper">
                    <input type="file" id="file" name="uploadfile"/>
                    <span class="placeholder" data-placeholder="Choose an image...">Choose an image...</span>
                    <label for="file" class="button">Browse</label>
                    <span id="upload-file-message"></span>
            <button type="submit" class="btn btn-primary">Upload</button>
        <div class="style16"></div>

upload controller

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public String uploadFile(@RequestParam("uploadfile") MultipartFile uploadfile) {

        try {
            // Get the filename and build the local file path
            String filename = uploadfile.getOriginalFilename();
            String directory = "/Sites/admissionsPortal/data";
            String filepath = Paths.get(directory, filename).toString();

            // Save the file locally
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filepath)));
        catch (Exception e) {

        return "redirect:/cert_prog";
    } // method uploadFile


var token = $("meta[name='_csrf']").attr("content");
    beforeSend: function(xhr) {
        xhr.setRequestHeader('X-CSRF-TOKEN', token);

var $form = $("#upload-file-input");
  $form.on("submit", function(e){
           url: $form.prop('action'),
           type: "POST",
           data: new FormData($("#upload-file-input")[0]),
           enctype: 'multipart/form-data',
           processData: false,
           contentType: false,
           cache: false,
           success: function () {
             // Handle upload success
             $("#upload-file-message").text("File succesfully uploaded");
           error: function () {
             // Handle upload error
             $("#upload-file-message").text("File not uploaded (perhaps it's too much big)");

The root cause of your error seems to be

nested exception is org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request

Which leads me to believe that your server side is working as intended, but the client is not sending data in the expected format.

Could you try changing up your ajax call to the following

// create a new form
var formData = new FormData();

// add your binary value to the file key
formData.append("file", fileBinary);

$.ajax({dataType : 'json',
    data : formData,                // add the form

Then on the server side, the uploaded file object will be present in the file parameter

public String uploadFile(@RequestParam("file") MultipartFile uploadfile) {

java - 400(Bad Request)Error, 400 (Bad Request) Error - Spring-boot File upload Using JQuery AJAX. 1518. March 02, 2017, at 06:21 AM. I am trying to upload a picture using thymeleaf ajax � Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question.Provide details and share your research! But avoid …. Asking for help, clarification, or responding to other answers.

Try to get formData like this

let uploadFile = $('#upload-file-input')[0];
let formData = new FormData(uploadFile);

send this formData in ajax data attribute.

jquery - Spring MVC Ajax 400 bad request - Stack Overflow, 400 (Bad Request) Error - Spring MVC File upload Using JQuery AJAX - S jquery ajax spring-mvc file-upload bad-request. I am trying to upload a picture using thymeleaf ajax and spring-boot

The cause of the issue is java.io.IOException: Stream closed. Most likely this means that some code has already called close() on HttpServletRequest's InputStream before multipart request parsing started.

A likely culprit can be a flawed implementation of servlet Filter that wraps the request with a caching decorator (that uses cached request content for most operations, except for multipart processing) and closes the input stream before passing the decorated request for further processing.

Debugging to see what calls close on HttpServletRequest's InputStream should reveal the culprit.

If that is difficult for some reason, you can also try disabling any third party filters (various validating, logging, monitoring filters, etc.) and see if the problem persists.

Spring Boot file upload example - Ajax and REST, This article shows you how to upload files in Spring Boot web Declares an extra jQuery webjar dependency, for Ajax requests in HTML form. pom. 8.4 Test a large movie file (100MB), the following error message will be� A 400 Bad Request Error occurs when a request sent to the website server is incorrect or corrupt, and the server receiving the request can’t understand it. Occasionally, the problem is on the website itself, and there’s not much you can do about that. But most of the time, the problem is one you might be able to solve—maybe you typed the address wrong, or maybe your browser cache is causing problems.

Spring MVC File Upload Example Tutorial, Spring File Upload,Spring MVC File Upload example MultipartFile, To utilize Apache Commons FileUpload for handling multipart requests, getMessage(); } } else { return "You failed to upload " + name + " because the file was empty. I am getting the 400-bad-request when uploading the file with more than 2 MB size . The most common reason for a 400 Bad Request error is because the URL was typed wrong or the link that was clicked on points to a malformed URL with a specific kind of mistake in it, like a syntax problem. This is most likely the problem if you get a 400 Bad Request error.

problem with uploading file using webservice using jquery in asp.net File upload using jquery ajax - IE 11 issue How to overwrite file in database using ajax call

4. jQuery. On the upload button click get the selected file and create a FormData object.. Append file in FormData object.. Send an AJAX request where pass the fd object and on successful callback check the response is 0 or not.

  • Do you ever hit the exception?
  • @MattClark Yes i do
  • @MattClark threw an IOException
  • I add the value to formData.append("file", $('input[type="file"]')[0]).val(); but got an error rg.springframework.web.multipart.MultipartException: The current request is not a multipart request –