How to receive binary file stream in Vue to realize PDF preview

How to receive binary file stream in Vue to realize PDF preview

Background Controller

@RequestMapping("/getPDFStream")
@ResponseBody
public void getPDFStream(HttpServletRequest request,HttpServletResponse response) {
 try {
  request.setCharacterEncoding("utf-8");
 } catch (UnsupportedEncodingException e) {
  logger.error("Set character set UnsupportedEncodingException");
 }
 String fileName = request.getParameter("fileName");
 //File pathString filePathname = Const.UPLOAD_HBFILE_PATH + "/" + fileName
   + ".pdf";
 File file = new File(filePathname);
 byte[] data = null;
 if (!file.exists()) {
  logger.error("Sorry File does not Exists!");
 } else {
  try {
   FileInputStream input = new FileInputStream(file);
   data = new byte[input.available()];
   input.read(data);
   response.getOutputStream().write(data);
   input.close();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   logger.error("pdf file processing exception");
  }
 }
}

Front desk reception

Encapsulate axios, request.js

import axios from 'axios'
/**
 * Method of encapsulating axios asynchronous request==================
 */
//Create an axios object-----------
const request = axios.create({
    //baseURL:'/dev-api', //Base path baseURL:process.env.VUE_APP_BASE_API, //Load different constant values ​​according to different environments // baseURL: '/',
    timeout: 50000, //Request timeout, 50000 milliseconds})
//Set up request interceptor=====================================
//Request interception--------------------
request.interceptors.request.use(config => {
    //Request interception config.data = {
        ...config.data,
        userId: sessionStorage.getItem('userId')
    }
    return config;
}, error => {
    //Exception return Promise.reject(error); //es6 writing });
//Set up response interceptor===================================
//Respond to interception--------------------
request.interceptors.response.use(response => {
    if(!response.data||response.data==""){
        return '{"flag":"failure","msg":"Unknown error"}';
    }
    return response.data;
},error =>{
    return Promise.reject(error);
})
export default request //Export custom created axios object for use by other components

Define method common.js

import request from '@/utils/request' //Import the encapsulated axios request method export function getPDFStream(param) {
   return request({
        url: 'xxxxxx/getPDFStream',
        method: 'post',
        // Pass parameter data: param,
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        responseType: 'blob',
        transformRequest: function(obj) {
            var str = [];
            for (var p in obj)
                str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
            return str.join("&");
        },
 })
}

Page Code

 <a-modal
  width="900px"
  title="File View"
  v-model="lookPdfFile"
  :footer="null"
  :forceRender="true"
  @ok="lookPdfFile"
>
  <div :style="{ height: '600px', minHeight: '500px', margin: '8px 0px' }">
     <iframe :src="pdfUrl" id="previewPdf" frameborder="0" style="width: 100%; height: 100%"></iframe>
  </div>
</a-modal>
//Import methodimport {getPDFStream} from "@/api/common";
//Define data
lookPdfFile:false, //Preview pdf
pdfUrl:'', // pdf path

Key code (after obtaining the file name, call the getPDFStream method to obtain the file stream)

 let _this = this;
 if(suffix == 'pdf'){
   getPDFStream({
     fileName: filename,
   }).then(res => {
     let reader = new window.FileReader();
     // Use readAsArrayBuffer to read the file. The result property will contain an ArrayBuffer object to represent the data of the read file. reader.readAsArrayBuffer(res);
     reader.onload = function(e) {
       const result = e.target.result
       const contentType = res.type
       // Generate blob image, requires parameters (byte array, file type)
       const blob = new Blob([result], { type: 'application/pdf' })
       // Use Blob to create a URL pointing to a typed array. URL.createObjectURL is a method of new Blob file, which can generate a normal URL and can be used directly, such as on img.src if (window.createObjectURL != undefined) { // basic
         _this.pdfUrl = window.createObjectURL(blob)+'#toolbar=0'
       } else if (window.webkitURL != undefined) { // webkit or chrome
         try {
           _this.pdfUrl = window.webkitURL.createObjectURL(blob)+'#toolbar=0'
         } catch (error) {

         }
       } else if (window.URL != undefined) { // mozilla(firefox)
         try {
           _this.pdfUrl = window.URL.createObjectURL(blob)+'#toolbar=0'
         } catch (error) {

         }
       }
     }
     this.$nextTick(() => {
       this.lookPdfFile = true;
     })
   })
   return;
 }

This is the end of this article about how to receive binary file streams in Vue to implement PDF preview. For more relevant Vue binary file stream PDF preview content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • vue-pdf realizes online file preview
  • How to preview pdf file using pdfjs in vue
  • Vue-pdf implements online preview of PDF files
  • Vue integrates PDF.js to implement PDF preview and add watermark steps
  • vue Sample code for using vue-pdf to implement PDF online preview
  • Vue implements online preview of PDF files and downloading (pdf.js)
  • Vue plugin development: How to use pdf.js to realize online preview of PDF documents on mobile phones
  • How to implement PDF file preview in Vue

<<:  Detailed summary of web form submission methods

>>:  Detailed explanation of padding and abbreviations within the CSS box model

Recommend

Introduction to the steps of deploying redis in docker container

Table of contents 1 redis configuration file 2 Do...

Detailed explanation of the execution process of mysql update statement

There was an article about the execution process ...

A detailed discussion of evaluation strategies in JavaScript

Table of contents A chestnut to cover it Paramete...

Learn MySQL execution plan

Table of contents 1. Introduction to the Implemen...

Full steps to create a password generator using Node.js

Table of contents 1. Preparation 2. Writing comma...

Complete steps to solve 403 forbidden in Nginx

The webpage displays 403 Forbidden Nginx (yum ins...

Details of the order in which MySQL reads my.cnf

Table of contents The order in which MySQL reads ...

Detailed explanation of Linux zabbix agent deployment and configuration methods

1. Install zabbix-agent on web01 Deploy zabbix wa...

Detailed example of SpringBoot+nginx to achieve resource upload function

Recently, I have been learning to use nginx to pl...

JS+Canvas draws a lucky draw wheel

This article shares the specific code of JS+Canva...

How to view the creation time of files in Linux

1. Introduction Whether the creation time of a fi...

Summary of common commands for Linux user and group management

This article summarizes the common commands for L...