我尝试下载一个文件。这个操作由ajax()
POST请求触发。该请求以JSON格式发送数据到控制器。控制器生成文件(字节)并将其发送回来。
JavaScript:
function getLicenseFile() {
$.ajax({
type: 'POST',
url: '<%=request.getContextPath()%>/licenses/rest/downloadLicenseFile',
dataType: 'json',
contentType: 'application/json;charset=UTF-8',
data: ko.mapping.toJSON(licenseModel),
success: function (data) {
console.log("in sucess")
},
error:function (xhr, ajaxOptions, thrownError){
console.log("in error")
}
});
}
控制器:
@RequestMapping(value = "/licenses/rest/downloadLicenseFile", method = RequestMethod.POST)
@ResponseStatus(value=HttpStatus.OK)
@ResponseBody
public void createLicenseFile(@Valid @RequestBody License license, HttpServletResponse response) throws Exception {
logger.debug("Contoller License in: "+ license);
byte[] licensedata = licenseEncodeDefaultService.createLicenseFile(license);
logger.debug("licenseData: " + new String(licensedata));
response.setHeader("Content-Disposition", "attachment; filename=\"" + license.getCustomer() + ".license\"");
response.getOutputStream().write(licensedata);
response.flushBuffer();
}
问题
- 浏览器应该打开下载框,但没有发生
- 响应在ajax函数的错误部分处理(但HTTP状态为
OK
)
那我做错了什么或者正确的做法是什么?
dataType: 'json'
,但是发送了某种许可文件?此外,我认为你不能使用ajax来下载文件。 - Musa