PDF文件在线预览

Jquery下的AJAX请求文件流的PDF预览

$.ajax({
	url: 'http://127.0.0.1:3000/getPdf', // 这里写入接口地址
	method: 'get', // 请求方式,这里我用的是get
	data: {Id:id}, // 这里是请求的参数
	mimeType: 'text/plain;charset=x-user-defined',//请求文件流的方式
	success: function (res) {
		// 这里可以处理预览时pdf文件空白
		let resLength = res.length
		let arr = new Uint8Array(new ArrayBuffer(resLength))
		for (let i = 0; i < resLength; i++) {
			arr[i] = res.charCodeAt(i)&0xff;
		}
		// 这边是转换成二进制流
		let blob = new Blob([arr], {
			type: 'application/pdf;charset=UTF-8'
		})
		const pdfView = window.URL.createObjectURL(blob)
		window.open(pdfView) // 在浏览器打开一个页签进行预览
	},
	error: function (err) {
		console.log('失败:', err)
	}
})

原生请求下的PDF文件预览

let xhr = new XMLHttpRequest();
let url = 'http://127.0.0.1:3000/getPdf?Id='+id;
xhr.open('get', url);
xhr.responseType = 'blob';
xhr.onload = function () {
	if (this.status === 200) {
		let blob = this.response;
		const pdfView = window.URL.createObjectURL(blob);
		window.open(pdfView) // 在浏览器打开一个页签进行预览
	}
}
xhr.send();

axios请求下的PDF预览

axios({
	methods: 'post',
	url: '',
	responseType: 'blob',
}).then(res => {
	let blob = new Blob([arr], {
		type: 'application/pdf;charset=UTF-8'
	})
	const pdfView = window.URL.createObjectURL(blob)
	window.open(pdfView) // 在浏览器打开一个页签进行预览
})
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值