在SpringBoot中使用Ajax方式MultipartFile上传失败

时间:2018-10-08 11:11:53

标签: jquery ajax spring spring-boot file-upload

虽然在正常的html和表单方式下上传效果很好,但是切换到ajax却失败了,并且在调试模式下 MultipartFile 总是 Null

code below works fine

//html code
<form method="POST" action="/api/upload" enctype="multipart/form-data" id="fileUploadForm">
    <input type="file" name="file"/>
    <input type="submit" value="submit" id="btnSubmit"/>
</form>

//java code
@RequestMapping(value = "/api/upload", consumes = "*/*", method = RequestMethod.POST)
public ResponseEntity upload(@RequestParam(value = "file", required = false) MultipartFile file, MultipartHttpServletRequest request) {
    return new ResponseEntity(fileService.upload(file), HttpStatus.OK);
}

以下代码不起作用

$(document).ready(function () {
    $("#btnSubmit").click(function (event) {
        event.preventDefault();
        var form = $('#fileUploadForm')[0];
        var data = new FormData(form);
        $.ajax({
            type: "POST",
            enctype: 'multipart/form-data',
            url: "/api/upload",
            data: data,
            processData: false,
            contentType: false,
            cache: false,
            timeout: 600000,
            success: function (data) {
                console.log("SUCCESS : ", data);
                $("#btnSubmit").prop("disabled", false);

            }
        });
    });
});

有人在这里提供一些线索吗?

1 个答案:

答案 0 :(得分:0)

事实上,这是一个jQuery问题...

只使用代码

var form = new FormData();
form.append("file", $("#fileInput")[0].files[0]);

完成