我的目标是将excel(.xlsx)文件发送到客户端并下载excel文件。下面是我的服务器端代码,该代码返回ResponseEntity。
@PostMapping(value = "/proccessFile")
public ResponseEntity<Resource> processFileAndDownload(@RequestBody String sheetName) throws FileNotFoundException, IOException
{
try
{
//some logic applied to the file CollibraOutputTemplateDataAttrName and the file is a saved in a tmp folder
collibraAutomationScript.processingFiles(sheetName);
//preparing CollibraOutputTemplateDataAttrName.xlsx for download
File file=new File("tmp/CollibraOutputTemplateDataAttrName.xlsx");
Path path = Paths.get(file.getAbsolutePath());
byte[] data = Files.readAllBytes(path);
ByteArrayResource resource = new ByteArrayResource(data);
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename="+ file.getName());
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(resource);
}catch (Exception e) {
// TODO: handle exception
}
return null;
}
ajax代码如下:
$.ajax({
type: "POST",
enctype: 'application/json',
url: 'http://localhost:8080/proccessFile',
data: nameOfSheet,
processData: false,
contentType: false,
success: function (response) {
var data = new Blob([response], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
var link=document.createElement('a');
link.href = window.URL.createObjectURL(data);
link.download='CollibraOutputTemplateDataAttrName.xlsx'
link.click();
},
error: function (error) {
console.log(error);
// process error
}
});
该文件正在下载中,但是当我尝试打开该文件时,显示“该工作簿由于损坏而无法被Microsoft Excel打开或修复”。我已经尝试过各种关于stackoverflow的解决方案来解决此问题,但是没有任何帮助。 在相同的代码中,我输入:'text / plain'并从服务器发送文本文件,它工作正常,下载的文本文件未损坏。不了解Excel文件在哪里出问题了?