后端返回PDF文件流,前端预览

后端返回PDF文件流,前端预览

  • 后端代码
    • 前端代码
      • 请求

后端代码

String filePath = "D:\\file\\1664354031701.pdf";
response.setContentType("application/pdf");
File file = new File(filePath);
if (file.exists()) {
    try (FileInputStream in = new FileInputStream(file);OutputStream out = response.getOutputStream()){
         byte[] b = new byte[1024 * 5];
         int n;
         while ((n = in.read(b)) != -1) {
             out.write(b, 0, n);
         }
         out.flush();
     } catch (IOException e) {
         logger.error(e.getMessage());
     }
 }

前端代码

请求

const response = await request({
    url: 'api/xxx',
    params: params,
    method: 'get',
    responseType: 'blob', // 设置响应的数据类型为一个包含二进制数据的 Blob 对象
    // responseType: 'arraybuffer', // 设置响应类型,否则页面会是空白pdf
    // responseType: 'multipart/form-data',
    // headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
    hideloading: false
  })

responseType设置成blob/arraybuffer都可以;

<template>
  <div class="container">
    <div class="word">
      <iframe
        :src="linkUrl"
        style="border: none"
        frameborder="0"
        height="100%"
        width="100%"
        scrolling="no"
        marginheight="0px"
        marginwidth="0px"
      ></iframe>
    </div>
  </div>
</template>
previewDoc(params).then(res => {
	const binaryData = []
	binaryData.push(res)
	const url = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/zip' }))
    this.linkUrl = window.HT_EnvConfig.fyptUrl + `/static/pdfjs/web/viewer.html?file=` + url
})
<style lang="less" scoped>
.container {
  width: 100%;
  height: 100%;
  background-color: transparent;
  .word {
    width: 100%;
    height: 100%;
  }
}
</style>

你可能感兴趣的:(java,前端)