首页 > 解决方案 > JAVA:上传多部分文件

问题描述

我正在为 Spring 控制器中的多部分文件上传而苦苦挣扎。我已经阅读了多个问题,谷歌,但似乎没有任何效果。

我明白了

error: "Bad Request"
exception: "org.springframework.web.multipart.support.MissingServletRequestPartException"
message: "Required request part 'file' is not present"

我的 BE 控制器:

@RequestMapping(value = "/zip", method = RequestMethod.POST)
public void readFile(@RequestParam("file") MultipartFile file) throws IOException { 
// code
}

FE,角度JS:

service.getZip = function getZip(file) {
    var formData = new FormData();
    formData.append('file', file);
    return $http({
        method: 'POST',
        url: CONSTANTS.readFile,
        data: formData,
        headers: {'Content-Type': undefined}
    }) .then(function (response) {
        var data = response.data;
        return data.id;
    });
}

HTML:

<input type="file" id="file" name="file" accept=".txt"/>

application.properties 还包含:

spring.http.multipart.enabled=false

更新:

遵循@Byeon0gam 建议从我的控制器中删除@RequestParam 时,我不再收到该错误,但是当涉及到控制器时,我的文件为空。尽管在 FE 服务中,正如我所见,它不是空的:

在此处输入图像描述

标签: javaangularjsspringmultipartform-data

解决方案


将您的 FE 中的 Content-Type 更改为:

headers: {'Content-Type': 'x-www-form-urlencoded'}

希望它对你有用。


推荐阅读