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:
|
<<: Detailed summary of web form submission methods
>>: Detailed explanation of padding and abbreviations within the CSS box model
With the continuous development of the Internet ec...
This article summarizes some simple principles of...
Tips for viewing History records and adding times...
We all know that Docker containers are isolated f...
This article example shares the implementation me...
Preface When I was working on a project recently,...
This article shares the specific code of JS canva...
In actual project development, if we have a lot o...
The pitfalls of MySQL read-write separation The m...
◆Add to favorites illustrate Click to add your we...
There are two ways to configure multiple projects...
Table of contents Too long to read Component styl...
Introduction to IPSec IPSec (Internet Protocol Se...
Table of contents Preface Target first step: Step...
For example: Copy code The code is as follows: <...