Java Spring使用ajax上传文件

时间:2018-08-03 15:43:32

标签: java ajax spring upload

如何通过ajax发送文件?

我知道如何使用默认格式将文件上传到服务器,我的意思是:

<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>

和该代码的控制器

@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);
    }
}

此代码有效,但我想用ajax编写。我尝试过:

$(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")
                }
            }
        })
    })
})

但是出现以下错误:

  

2018-08-03 21:00:29.317错误9204 --- [nio-8080-exec-3]   o.a.c.c.C。[。[。[/]。[dispatcherServlet]:的Servlet.service()   路径[]中的servlet [dispatcherServlet]抛出异常   [请求处理失败;嵌套异常为   org.springframework.web.multipart.MultipartException:无法解析   多部分servlet请求;嵌套的异常是java.io.IOException:   org.apache.tomcat.util.http.fileupload.FileUploadException:   请求被拒绝,因为未找到多部分边界],其中   根本原因

我在Google中进行了搜索,但没有找到任何解决方案。

1 个答案:

答案 0 :(得分:1)

您没有在$ .ajax调用中提交任何“数据”,因此没有发送文件并出现此错误。参见带有示例的相关主题:

Sending multipart/formdata with jQuery.ajax