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

Simple principles for web page layout design

This article summarizes some simple principles of...

Tips for viewing History records and adding timestamps in Linux

Tips for viewing History records and adding times...

Three ways to communicate between Docker containers

We all know that Docker containers are isolated f...

Detailed usage of Vue more filter widget

This article example shares the implementation me...

Solution for front-end browser font size less than 12px

Preface When I was working on a project recently,...

JS canvas realizes the functions of drawing board and signature board

This article shares the specific code of JS canva...

Analysis of the use of the MySQL database show processlist command

In actual project development, if we have a lot o...

Common solutions for Mysql read-write separation expiration

The pitfalls of MySQL read-write separation The m...

The most basic code for web pages

◆Add to favorites illustrate Click to add your we...

How to configure multiple projects with the same domain name in Nginx

There are two ways to configure multiple projects...

Solution to the ineffective global style of the mini program custom component

Table of contents Too long to read Component styl...

Alibaba Cloud Ubuntu 16.04 builds IPSec service

Introduction to IPSec IPSec (Internet Protocol Se...

Simple implementation of mini-vue rendering

Table of contents Preface Target first step: Step...

Using an image as a label, the for attribute does not work in IE

For example: Copy code The code is as follows: <...