后端返回二進制文件流,前端vue實現在線預覽


首先后端的接口返回的只要二進制文件流,不要其他東西,我之前有別的字段,二進制流就得轉成字符串返給前端,前端就還要再把字符串轉成二進制流,沒必要


import axios from 'axios' export const view=(url,body,params)=>{ // let token = getTokens() // let queryParams = {docTemplate:'policy'} // Object.assign(queryParams, params) return axios({ method: 'post', url: `${url}`, data: params, query: params, headers:{ 'Content-Type':"application/json;charset=UTF-8" }, responseType: "blob" }) } export const img=(url,body,params)=>{ // let token = getTokens() // let queryParams = {docTemplate:'policy'} // Object.assign(queryParams, params) return axios({ method: 'post', url: `${url}`, data: params, query: params, headers:{ 'Content-Type':"application/json;charset=UTF-8" }, responseType: "arraybuffer"//這是圖片的返回類型 }) }

這是封裝axios,請求方法(post為例)↑↑↑↑

 import {view,img} from '@/assets/js/axios.js'//在需要用的.vue文件引入

pdf的話利用pdf.js插件↓↓↓↓↓

 await view('/document/viewDocument','',{ docID:data.docID,docTemplate:this.Type}).then(res=>{
                console.log(res)

                var blob = new Blob([res.data], {
                  type: 'application/pdf'})//這個是Content-Typele的type類型(https://tool.oschina.net/commons)
                console.log('blob=======')//
                console.log(blob)
                let fileURL= URL.createObjectURL(blob)
                let url=encodeURIComponent(fileURL)
                console.log(fileURL)//blob:http://localhost:8080/20a92c23-9734-4cea-8d6b-cff2e2a6e46b
                console.log(url)//blob%3Ahttp%3A%2F%2Flocalhost%3A8080%2F20a92c23-9734-4cea-8d6b-cff2e2a6e46b
                this.src = `http://pekbjdwdcs010:8098/pdf/web/viewer.html?file=${url}`;

                //
              }
            )

圖片的話↓↓↓↓↓

await img('/document/viewDocument','',{ docID:data.docID,docTemplate:this.Type}).then(res=>{
                console.log(res)
              var url='data:image/png;base64,' + btoa(new Uint8Array(res.data).reduce((data, key) => data + String.fromCharCode(key), ''))
              // var url=`data:image/png;base64,${data.docStream}`
              this.src=url
              console.log(url)
              }
            )

 

 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM