[英]Excel file getting corrupted while downloading using PowerShell/Curl
[英]Excel File getting Corrupted when Downloading from S3
目標:從 UI 上的 S3 存儲桶下載文件(Angular)
服務
public byte[] downloadFileFromS3(String dfileName) {
byte[] buffer = "Empty".getBytes();
try {
S3Object s3object = conn.getObject(bucketName, dfileName);
S3ObjectInputStream inputStream = s3object.getObjectContent();
buffer = new byte[(int) s3object.getObjectMetadata().getContentLength()];
while (inputStream.read(buffer) > 0) {
inputStream.read();
}
} catch (Exception e) {
LOG.error("Exception occurred when accessing {} from S3 {}", dfileName, e.getMessage());
}
return buffer;
}
控制器
@GetMapping("/download")
public ResponseEntity<Resource> getFilefromS3(@RequestParam(name = "fileName") String fileName) {
byte[] file = awsStorageHelper.downloadFileFromS3(fileName);
return ResponseEntity.ok().header("Content-Type", MediaType.APPLICATION_OCTET_STREAM_VALUE)
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
.body(new ByteArrayResource(file));
}
實現: spring 應用程序部署在可以訪問 S3 的 EC2 實例上。 應用程序將讀取所需的文件並將字節數組傳遞給角度應用程序。
問題:下載 .docx 或 .txt 等文件時,文件會按預期下載,但如果下載 .xlsx 或 .xls 文件,文件會損壞。 在壓縮文件的情況下,當 .zip 文件的內容為 .docx 或 .txt 時,.zip 文件下載沒有問題,但如果 .zip 文件包含 .xlsx 或 .xls 文件,則 .zip 文件也會損壞。
這里到底出了什么問題,有沒有更好的方法來從 S3 下載文件?
解決方案:無需在控制器中將“輸入流”轉換為“字節數組作為資源”。
傳遞從 S3 服務方法接收到的相同“輸入流”,並在控制器中作為“輸入流作為資源”傳遞。
服務:
public InputStream downloadFileFromS3(String dfileName) {
LOG.info("Downloading File {} ", dfileName);
try {
S3Object s3object = conn.getObject(bucketName, dfileName);
return s3object.getObjectContent();
} catch (Exception e) {
throw new AeCoreException("Exception Occured Accessing File " + dfileName,
HttpStatus.INTERNAL_SERVER_ERROR);
}
}
控制器:
@GetMapping("/download")
public ResponseEntity<InputStreamResource> getFilefromS3(@RequestParam(name = "fileName") String fileName) {
InputStream file = awsStorageHelper.downloadFileFromS3(fileName);
return ResponseEntity.ok().header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE)
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
.body(new InputStreamResource(file));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.