我有一个关于在springboot中使用HttpEntity下载文件的问题。
文件的ID作为参数传递,并且从控制器接收参数。 但是,该文件未下载,并显示错误消息。
我的代码返回错误吗? 如果有任何问题,请通知我。
这是我的代码: -filedownload链接单击-> downloadFile.json->控制器映射-> filedownalod->返回消息(“成功”);
function downloadFile(fileId){
if(fileId != null){
$.ajax({
type:"post",
url: [[@{|/downloadScriptFile.json|}]],
data: JSON.stringify(fileId),
contentType: "application/json; charset=utf-8",
dataType: "json",
success : function(response){
console.log("SUCCESS");
}
error : function(xhr, status, err){
console.log("download Faile");
}
});
}
}
@RequestMapping("/downloadScriptFile.json")
public @ResponseBody HttpEntity<byte[]> downloadScriptFile(@RequestBody( required = true) Integer fileId, HttpServletRequest request) throws IOException
{
System.out.println("fileId: " + fileId);
ScriptFile scriptFile = scriptService.getScriptFileById(fileId);
byte[] fileBytes = null;
try {
fileBytes = scriptService.getScriptFileByte(scriptFile);
}
catch (Exception e) {
throw new ResourceNotFoundException();
}
String fileName = scriptFile.getFileName();
String browser = request.getHeader("User-Agent");
if(browser != null) {
if(browser.contains("MSIE") || browser.contains("Trident")) {
fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
}else {
fileName = new String((scriptFile.getFileName()).getBytes("UTF-8"),"ISO-8859-1");
}
System.out.println("fileName : " + fileName );
HttpHeaders header = new HttpHeaders();
header.setContentType(new MediaType("application", "unknown"));
header.setContentLength(fileBytes.length);
header.setContentDispositionFormData("attachment", fileName);
return new HttpEntity<byte[]>(fileBytes, header);
}