控制台出现提示:
从接口拿到的文件流:
1.响应头: 2.请求头:
原因: 接收到文件流后,格式不对导致pdf.js无法浏览。
解决方案: 收到文件流后,使用响应的数据创建一个 blob,然后使用该 blob 创建一个 url。
const blob = new Blob([data], {type: 'application/pdf'})
let url = window.URL.createObjectURL(blob)
我的代码案例:
src/utils/request.js
import axios from 'axios'
import { getToken } from '@/utils/auth'
import { Notification, MessageBox, Message, Loading } from 'element-ui'
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
const service = axios.create({
baseURL:window.prod_config.BASE_URL,
timeout: 10000
})
service.interceptors.request.use(config => {
const isToken = (config.headers || {}).isToken === false
if (getToken() && !isToken) {
config.headers['Authorization'] = 'Bearer ' + getToken()
}
if (config.method === 'get' && config.params) {
let url = config.url + '?' + tansParams(config.params);
url = url.slice(0, -1);
config.params = {};
config.url = url;
}
return config
}, error => {
console.log(error)
Promise.reject(error)
})
let isReFreshPadding=true
service.interceptors.response.use(res => {
const code = res.data.code || 200;
const msg = errorCode[code] || res.data.msg || errorCode['default']
if(res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer'){
return res.data
}
if (code !== 200) {
Notification.error({
title: msg
})
return Promise.reject('error')
} else {
return res.data
}
},
error => {
console.log('err' + error)
let { message } = error;
if (message == "Network Error") {
message = "后端接口连接异常";
}
Message({
message: message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
export function downStream(url,params) {
return service.get(url, {
responseType: 'blob'
}).then(res => {
return res
}).catch((r) => {
console.error(r)
})
}
export default service
src/api/user/userApi.js
import { downStream } from '@/utils/request'
export function previewFile(id) {
return downStream('/order/printUser/printFile/preview/' + id)
}
user.vue
<script>
import {
previewFile
} from '@/api/user/userApi'
pdfDlg(fileId){
previewFile(fileId).then((response) => {
const blob = new Blob([response], {type: 'application/pdf'})
this.src = window.URL.createObjectURL(blob)
this.pdfDialogVisible = true
}).catch(err => {
console.log('err:', err)
})
},
|