前端代碼:<a?:href="'/api/down-api/down'"?download="down.xlsx">下載</a>后端代碼:接口:@ApiOperation(value?=?"下載")
@GetMapping("/down")
public?void?downTemplate(HttpServletResponse?response)?{
????String?fileName?=?"down.xlsx";
????couponService.down(response,?fileName);
}實現類:public?void?down(HttpServletResponse?response?,String?filename)?{
????//?讀取要下載的文件,保存到文件輸入流
????FileInputStream?in?=?null;
????OutputStream?out?=?null;
????try?{
????????//?得到要下載的文件(文件存放在項目resources的static文件夾里)
????????File?file?=?new?File("src\\main\\resources\\static"?+?"\\"?+?filename);
????????//?如果文件不存在
????????if?(!file.exists())?{
????????????throw?new?BusinessException("Could?not?read?file");
????????}
????????//?設置響應頭,控制瀏覽器下載該文件
????????response.setHeader("Content-Disposition",?"attachment;filename="+filename);
????????response.setHeader("Content-Type",?"application/octet-stream;charset=UTF-8");
????????response.setContentType("application/octet-stream");
????????in?=?new?FileInputStream(file);
????????//?創建輸出流
????????out?=?response.getOutputStream();
????????//?創建緩沖區
????????byte?buffer[]?=?new?byte[1024];
????????int?len?=?0;
????????//?循環將輸入流中的內容讀取到緩沖區當中
????????while?((len?=?in.read(buffer))?>?0)?{
????????????//?輸出緩沖區的內容到瀏覽器,實現文件下載
????????????out.write(buffer,?0,?len);
????????}
????????//?關閉文件輸入流
????????in.close();
????????//?關閉輸出流
????????out.close();
????}?catch?(Exception?e)?{
????????e.printStackTrace();
????}
}
使用a標簽進行下載excel文件,打開下載后的文件內容為空,這是為什么?
慕沐1134704
2019-04-19 11:24:36