Java 作为InputStreamResource返回时Excel文件未打开
我正在尝试创建一个API,它正在发送excel文件的InputStreamResource。它是在服务器端根据表的数据创建的 当我从postman点击这个api时,excel文件没有打开,并且说它没有正确的扩展名或者文件已损坏 我已将文件保存在服务器端,该服务器端可以正常打开 也尝试发送HTTP实体。还是有同样的反应 这是我的控制器Java 作为InputStreamResource返回时Excel文件未打开,java,spring,rest,spring-boot,file,Java,Spring,Rest,Spring Boot,File,我正在尝试创建一个API,它正在发送excel文件的InputStreamResource。它是在服务器端根据表的数据创建的 当我从postman点击这个api时,excel文件没有打开,并且说它没有正确的扩展名或者文件已损坏 我已将文件保存在服务器端,该服务器端可以正常打开 也尝试发送HTTP实体。还是有同样的反应 这是我的控制器 @GetMapping(path = RestMappingConstants.AdminRequestUri.DOWNLOAD_A2TO_INTERVIEWER_
@GetMapping(path = RestMappingConstants.AdminRequestUri.DOWNLOAD_A2TO_INTERVIEWER_EXCEL)
public ResponseEntity<InputStreamResource> downloadA2ToInterviewPaymentExcel( ) throws IOException{
ByteArrayInputStream in = a2AdminService.downloadA2ToInterviewPaymentExcel();
HttpHeaders headers = new HttpHeaders();
//InputStream res=A2AdminController.class.getClassLoader().getResourceAsStream("payment.xlsx");
headers.add("Content-Disposition", "attachment; filename=PaymentDetails.xlsx");
headers.setContentType(new MediaType("application", "vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
return ResponseEntity
.ok()
.headers(headers)
.body(new InputStreamResource(in));
}
@GetMapping(path=RestMappingConstants.AdminRequestUri.DOWNLOAD\u A2TO\u concert\u EXCEL)
公共响应下载A2toInterviewPaymentExcel()引发IOException异常{
ByteArrayInputStream in=a2AdminService.downloadA2ToInterviewPaymentExcel();
HttpHeaders=新的HttpHeaders();
//InputStream res=A2AdminController.class.getClassLoader().getResourceAsStream(“payment.xlsx”);
添加(“内容处置”、“附件;文件名=PaymentDetails.xlsx”);
setContentType(新的MediaType(“application”,“vnd.openxmlformats of cedocument.spreadsheetml.sheet”);
返回响应性
.ok()
.标题(标题)
.机构(新输入流资源(in));
}
这是我的服务课
@Override
public ByteArrayInputStream downloadA2ToInterviewPaymentExcel() throws IOException {
List<A2ToInterviewerPaymentEntity> a2ToInterviewerPaymentEntityList = a2AdminDao.getApprovedPaymentList();
// FileOutputStream file=new FileOutputStream("payment.xlsx");
// convert to excel
String[] columns = { "Id", "Amount", "PaymentMode", "PaymentType", "TransactionId", "InterviewScheduleId",
"EmployerToPaymentEntityId", "PaymentStatus" };
try (Workbook workbook = new XSSFWorkbook(); ByteArrayOutputStream out = new ByteArrayOutputStream();) {
Sheet sheet = workbook.createSheet("payment");
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setColor(IndexedColors.BLUE.getIndex());
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle.setFont(headerFont);
// Row for Header
Row headerRow = sheet.createRow(0);
// Header
for (int col = 0; col < columns.length; col++) {
Cell cell = headerRow.createCell(col);
cell.setCellValue(columns[col]);
cell.setCellStyle(headerCellStyle);
}
int rowIdx = 1;
for (A2ToInterviewerPaymentEntity paymentEntity : a2ToInterviewerPaymentEntityList) {
Row row = sheet.createRow(rowIdx++);
row.createCell(0).setCellValue(paymentEntity.getId());
row.createCell(1).setCellValue(paymentEntity.getAmount());
row.createCell(2).setCellValue("UPI");
row.createCell(3).setCellValue("TRANSFER");
row.createCell(4).setCellValue(paymentEntity.getTransactionId());
row.createCell(5).setCellValue(paymentEntity.getInterviewSchedule().getId());
row.createCell(6).setCellValue(paymentEntity.getEmployerToA2PaymentEntity().getId());
row.createCell(7).setCellValue(paymentEntity.getPaymentStatus().toString());
}
workbook.write(out);
// workbook.write(file);
byte[] arr = out.toByteArray();out.flush();out.close();
return new ByteArrayInputStream(arr);
}
}
@覆盖
public ByteArrayInputStream下载A2ToInterviewPaymentExcel()引发IOException{
列出a2ToInterviewerPaymentEntityList=a2AdminDao.getApprovedPaymentList();
//FileOutputStream文件=新的FileOutputStream(“payment.xlsx”);
//转换为excel
String[]列={“Id”、“Amount”、“PaymentMode”、“PaymentType”、“TransactionId”、“InterviewScheduleId”,
“EmployeeToPaymentEntityId”、“PaymentStatus”};
尝试(工作簿工作簿=新XSSF工作簿();ByteArrayOutputStream out=新ByteArrayOutputStream();){
工作表=工作簿。创建工作表(“付款”);
Font-headerFont=workbook.createFont();
headerFont.setBold(真);
setColor(IndexedColors.BLUE.getIndex());
CellStyle headerCellStyle=工作簿.createCellStyle();
headerCellStyle.setFont(headerFont);
//标题行
Row headerRow=sheet.createRow(0);
//标题
for(int col=0;col
从postman下载的文件是输入数组流。您需要在前端代码中处理此流,以便将其转换为相应的文件。为此,前端角度代码如下所示
var result = this.budgetService.downloadEstimates(this.userDetail.userId);
result.subscribe(
data => {
this.utilitiesService.hideLoader();
const blob = new Blob([data], { type: 'text/csv' });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(blob, 'results.xlsx');
}else{
//let blob = data;
let a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = 'results.xlsx';
document.body.appendChild(a);
a.click();
}
},
error => {
this.utilitiesService.showInformation('Download has failed', 'Error');
})
}
downloadResultSubscriber.unsubscribe();
});
要直接从控制器下载文件,请使用下面的代码段,但这应该在前端api开始集成api时立即恢复
@GetMapping(path = /download)
public void downloadFile(HttpServletResponse httpServletResponse) throws IOException{
File f = // your file here;
httpServletResponse.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
httpServletResponse.setContentLength(f.length);
httpServletResponse.setHeader("Content-Disposition", "attachment; filename=PaymentDetails.xlsx");
FileCopyUtils.copy(f, httpServletResponse.getOutputStream());
httpServletResponse.flushBuffer();
}
在控制器中尝试以下代码:
ResponseEntity.ok()
.contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" +yourFileName".xlsx")
.body(yourFileInByteArray);
我解决了这个问题。这是邮递员的问题。当我试图通过超越安全性来使用相同的API浏览器时,它工作得很好
我想邮递员是在用下载的excel文件制造问题我需要做什么,以便用户只需单击按钮,文件就可以下载我该如何测试我的api是否正常工作以及生成的excel文件是否正确?您肯定需要一个前端代码来测试您的api,但是要测试excel文件,您可以创建一个简单的java类并验证文件内容。从postman测试api的另一个选项是修改控制器以直接下载文件,而不是返回responseEntity。在这种情况下,您可以测试您的api,但必须在前端开始集成它之前修改代码。我如何从控制器直接下载文件这不会有帮助,因为下载文件不同于将其作为响应实体发送感谢您的建议。但这帮不了我