服務端代碼:javascript
public ResponseEntity<Resource> exportsequence(@PathVariable String modelname) throws IOException { XSSFWorkbook wb = constructExportData(modelname); ByteArrayOutputStream os = new ByteArrayOutputStream(); wb.write(os); InputStreamResource resource = new InputStreamResource(os.toInputStream()); os.close(); return ResponseEntity.ok().contentType(MediaType.valueOf("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")).body(resource); } /** * * * @param modelName */ private XSSFWorkbook constructExportData(String modelName) { XSSFWorkbook wb = new XSSFWorkbook(); XSSFSheet sheet = wb.createSheet(ExcelFileHandlerUtil.SEQUENCE_SHEET_FC); XSSFRow row = sheet.createRow(0); XSSFCell cell = row.createCell(0); cell.setCellValue(ExcelFileHandlerUtil.MODEL_STRING); return wb; }
客戶端代碼:java
return this.http.get(`${this.resourceUrl}/exportsequence/${modelName}`);
用這個下載的時候二進制內容都是正確的,但是打開文件老報錯,打不開。app
原來要在請求上加一個 responseTypethis
修改代碼以下:code
const requestOptions = { responseType: ResponseContentType.Blob }; return this.http.get(`${this.resourceUrl}/exportsequence/${modelName}`, requestOptions);
記得加:orm
import {Http, Response,ResponseContentType } from '@angular/http';