У меня есть вопрос о загрузке файла с использованием HttpEntity в springboot.
Идентификатор файла передается в качестве параметра, а параметр принимается от контроллера.
Однако файл не загружается и появляется сообщение об ошибке.
Мой код возвращает что-то не так?
Если что-то не так, пожалуйста, дайте мне знать.
Это мой код:
- нажмите на ссылку загрузки файла -> 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);
}