uniapp小程序 处理后台的arraybuffer类型数据并实现预览pdf

1.将responseType设置成arraybuffer
未设置时就会返回像乱码一样的东西
在这里插入图片描述
成功拿到
在这里插入图片描述
2.用文件管理器将文件写入本地

const fileManager = uni.getFileSystemManager(); // 获取全局的文件管理器
const filePath = `${wx.env.USER_DATA_PATH}/${this.bookList[index].name}.pdf`; // 文件存储到本地的路径)
// this.bookList[index].name是后台传过来的pdf的名字,除了这一处其他都可以不用改
fileManager.writeFile({
  data: res.data, // 拿到的arraybuffer数据
  filePath: filePath,	
  encoding: 'binary',
  success: res => {
    console.log(res);// 成功了的话这里会打印 writeFile:ok
  }
})

3.直接打开写入本地的文件

uni.openDocument({ // 直接打开
  filePath: filePath,	// 这里填上面写入本地的文件路径
  fileType: 'pdf',
  showMenu: true, // 右上角是否有可以转发分享的功能,配不配随意
  success: res => {
	console.log('打开文档成功');
 }
})

我试了一下移动端是自动打开微信浏览器,用开发者工具在pc端调试是自动打开了wps🤔

完整代码:

previewFile(index) {	// 循环bookList的index
  uni.showLoading({
	title: '正在加载...'
  })
  this.$request({	// 封装了的request,直接调用了
	url: '',
	method: 'POST',
	data: {},
	header: {},
	responseType: 'arraybuffer' // !
  }).then(res => {
	const fileManager = uni.getFileSystemManager(); // 获取全局的文件管理器
	const filePath = `${wx.env.USER_DATA_PATH}/${this.bookList[index].name}.pdf`; // 文件存储到本地的路径
	fileManager.writeFile({
		data: res.data,	// 拿到的arraybuffer数据
		filePath: filePath,
		encoding: 'binary',
		success: res => {
			uni.openDocument({ // 直接打开
				filePath: filePath,
				fileType: 'pdf',
				showMenu: true,
				success: res => {
					uni.hideLoading();
				}
			})
		}
	})
})
},
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值