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

One line of CSS code to achieve the integration of avatar and national flag

It’s National Day, and everyone is eager to celeb...

Detailed explanation of primary keys and transactions in MySQL

Table of contents 1. Comments on MySQL primary ke...

A brief discussion on the differences between FTP, FTPS and SFTP

Table of contents Introduction to FTP, FTPS and S...

Solutions to MySql crash and service failure to start

I have been in contact with PHP for so long, but ...

How to run Hadoop and create images in Docker

Reinventing the wheel, here we use repackaging to...

14 Ways to Create Website Content That Engages Your Visitors

When I surf the Net, I often see web sites filled...

How to sort a row or column in mysql

method: By desc: Neither can be achieved: Method ...

How to install Nginx in a specified location in Centos system

How to install Nginx in a specified location in C...

Example code of vue icon selector

Source: http://www.ruoyi.vip/ import Vue from ...

Window.name solves the problem of cross-domain data transmission

<br />Original text: http://research.microso...

How to use CSS to achieve data hotspot effect

The effect is as follows: analyze 1. Here you can...

Docker FAQ

Docker only maps ports to IPv6 but not to IPv4 St...

Detailed tutorial on installing MySQL 8.0.20 database on CentOS 7

Related reading: MySQL8.0.20 installation tutoria...

Navicat connection MySQL error description analysis

Table of contents environment Virtual Machine Ver...