当我尝试将数据上传到Spring MVC并使用Spring MVC下载文件时,我有一种奇怪的行为。
这是服务器端:
@RequestMapping(method = RequestMethod.POST, value = "/generate", consumes = {"multipart/form-data"}, produces = {"multipart/form-data"})
public ResponseEntity generate(@RequestParam final MultipartFile myMultipartFile)
{
ResponseEntity responseEntity = null ;
try
{
responseEntity = this.generateInternal(myMultipartFile) ;
}
catch (IOException ioException)
{
responseEntity = ResponseEntity.status(HttpStatus.FORBIDDEN).body(ioException.getMessage()) ;
}
return responseEntity ;
}
(1)另一方面,以下代码正常运行:
var input = document.getElementById('myFile');
var xhr = new XMLHttpRequest() ;
var formData = new FormData();
formData.append("myMultipartFile", input.files[0]) ;
xhr.open('POST', "http://localhost:8080/generate", true) ;
xhr.responseType = "blob" ;
xhr.withCredentials = false ;
xhr.onreadystatechange = function ()
{
if (xhr.readyState == 4 && xhr.status == 200)
{
var blob = xhr.response;
console.log("This code is working properly, I can download the file") ;
}
};
xhr.send(formData) ;
(2)但是......以下代码无法正常工作:(
var xhr = new XMLHttpRequest() ;
var formData = new FormData();
formData.append("myMultipartFile", "The content is a YAML") ;
xhr.open('POST', "http://localhost:8080/generate", true) ;
xhr.responseType = "blob" ;
xhr.withCredentials = false ;
xhr.onreadystatechange = function ()
{
if (xhr.readyState == 4 && xhr.status == 200)
{
var blob = xhr.response;
console.log("This code is never executed, I got a 402 HTTP Error") ;
}
};
xhr.send(formData) ;
在第二个例子(2)中,我在浏览器中出错(406(Not Acceptable))。如果我添加依赖性' spring-boot-starter-actuator'在Java项目中(为了监控请求 - 使用" / trace"),我收到了以下响应信息:
response: {
X-Application-Context: "application",
status: "400"
}
之前的回复与正确回答(1)完全不同:
response: {
X-Application-Context: "application",
Content-Type: "multipart/form-data;charset=UTF-8",
Transfer-Encoding: "chunked",
Date: "Mon, 20 Jun 2016 15:43:52 GMT",
status: "200"
}
(1)和(2)之间的唯一区别是发送文件的机制:
有没有人有这种奇怪的行为?你是怎么解决的?
非常感谢。
此致 帕。