Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize pdf Preview by receiving binary File Stream in Vue

Shulou Source: shulou.com Published: 2022-06-02 07:36:07 09月22日 Update

This article mainly explains the "Vue receive binary file stream how to achieve pdf preview", the article explains the content is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in-depth, together to study and learn "receive binary file stream in Vue how to achieve pdf preview" bar!

Background Controller

@ RequestMapping ("/ getPDFStream") @ ResponseBodypublic 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 path String 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 handling exception") Reception at the front desk

Encapsulate axios, request.js

Import axios from 'axios'/** * method for encapsulating axios asynchronous requests = * / create an axios object-const request = axios.create ({/ / baseURL:'/dev-api',// basic path baseURL:process.env.VUE_APP_BASE_API,// loads different constant values / / baseURL:'/' depending on the environment, timeout: 50000 jaw / request timeout 50000 milliseconds}) / / set request interceptor = = / / A request to intercept-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 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 / / exports custom created axios objects 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 parameters 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

/ / Import method import {getPDFStream} from "@ / api/common"; / / define datalookPdfFile:false,// preview pdfpdfUrl:'',// pdf path

Key code (after getting the file name, call the getPDFStream method to get 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, and the result property will contain an ArrayBuffer object to represent the data reader.readAsArrayBuffer (res) of the file being read Reader.onload = function (e) {const result = e.target.result const contentType = res.type / / generate blob image, requires parameter (byte array, file type) const blob = new Blob ([result], {type: 'application/pdf'}) / / create a URL pointing to typed array using Blob, URL.createObjectURL is the method of new Blob file You can generate a normal url, which can be used directly For example, 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;} Thank you for reading, this is the content of "receiving binary file stream in Vue how to achieve pdf preview". After the study of this article, I believe you have a deeper understanding of how to achieve pdf preview of receiving binary file stream in Vue, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Files methods binaries objects paths learning encapsulation differences code content parameters arrays types interceptors generation normal lieutenant general key writing foreground Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Shulou Technology Shulou Information Linux OPPO Reno