場景
直接展示外部系統返回的獲取文件流時出現了跨域問題:
解決辦法
1. 外部系統返回的請求頭中調整(但是其他系統不會給你改的)
2. 我們系統后臺獲取文件流并轉為新的文件流提供給前端
/** 獲取傳入url文件流 */
@GetMapping("/getFileStream")
public ResponseEntity<org.springframework.core.io.Resource> getFileStream(@RequestParam("url") String url,@RequestParam(value = "download", required = false) boolean download)throws UnsupportedEncodingException, BusinessException {// 返回流ByteArrayOutputStream outputStream = OkHttpClientUtil.get(url);if (null == outputStream) {throw new BusinessException("文件流為空", ServiceResponseStatus.SERVICE_ERROR);}String baseName = FilenameUtils.getBaseName(url);String extension = FilenameUtils.getExtension(url);String filename =URLEncoder.encode(baseName, "UTF-8") + FilenameUtils.EXTENSION_SEPARATOR + extension;MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM;if (FxCommFileType.PDF.getSuffix().toLowerCase().equals(extension)) {mediaType = MediaType.APPLICATION_PDF;}StringBuilder headerValues = new StringBuilder();if (download) {headerValues.append("attachment;");}headerValues.append("filename=").append(filename);return ResponseEntity.ok().contentType(mediaType).header(HttpHeaders.CONTENT_DISPOSITION, headerValues.toString()).body(new ByteArrayResource(outputStream.toByteArray()));
}