Farhad Kurbanov
Farhad Kurbanov

Reputation: 13

java Spring upload file with ajax

How to send a file via ajax?

I know how to upload files to the server with default form, I mean this:

<div class="addBook" >
<form id="add" action="/add" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <label for="title">Title</label>
        <input name="title" type="text" class="form-control" id="title" placeholder="title">
    </div>
    <div class="form-group">
        <label for="description">Description</label>
        <textarea name="description" class="form-control" id="description" rows="3"></textarea>
    </div>
    <div class="form-group">
        <label for="picture">file input</label>
        <input name="picture" type="file" class="form-control-file" id="picture">
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>

and controller for this code

@RequestMapping(value = "/add", method = RequestMethod.POST)
public ResponseEntity<String> add(
        @RequestParam(value = "title",required = false)String title,
                  @RequestParam(value = "description",required = false)String description,
                  @RequestParam(value = "picture",required = false)MultipartFile file){
    Book book = new Book();
    book.setFileName(addFile(file));
    book.setTitle(title);
    book.setDescription(description);


    return new ResponseEntity<String>("index", HttpStatus.OK);
    }
}

This code works, but I want to write it by ajax. I tried this:

$(document).ready(function () {
    $("#add").submit(function (e) {
        e.preventDefault();
        $.ajax({
            url:'/add',
            type:'POST',
            contentType:"multipart/form-data",
            statusCode:{
                409:function () {
                    $("#mess").html('<b>Логин занят</b>');
                },
                200:function(){
                    console.log("successfull")
                }
            }
        })
    })
})

But I get the following error:

2018-08-03 21:00:29.317 ERROR 9204 --- [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: Failed to 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] with root cause

I searched in Google, but didn't find any solution.

Upvotes: 1

Views: 566

Answers (1)

Andrei Prakhov
Andrei Prakhov

Reputation: 206

You have submitted no 'data' in your '$.ajax' call, therefore you send no file and get this error. See related topic with example:

Sending multipart/formdata with jQuery.ajax

Upvotes: 1

Related Questions