Preview the pdf file stream of the specified link on the mobile terminal

Scenes

A cross-domain problem occurred when directly displaying the file stream returned by an external system:
Insert image description here

Solution

1. Adjust the request header returned by the external system (but other systems will not change it for you)

Insert image description here

2. Our system obtains the file stream in the background and converts it into a new file stream to provide to the front end.

/** 获取传入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()));
}

Guess you like

Origin blog.csdn.net/ZHAI_KE/article/details/132279186