预览
在做uniapp开发之前必须明确一个事情:使用了非 H5 端不支持的 API 小程序和 App 的 js 运行在jscore下而不是浏览器里,没有浏览器专用的js对象,比如document、dom、blob、xmlhttp、cookie、window、location、navigator、localstorage、websql、indexdb、webgl等对象。以下这种方式就不支持在app上预览。
uni.request({
url:'http://xxxxxxx',
responseType: 'arraybuffer',
success: (response) => {
if(!response){
uni.showToast({
title:"协议预览失败",
duration:2000
});
}
let pdfData = response.data;
let blob = new Blob([ pdfData], {
type: 'application/pdf;charset=UTF-8'
})
pdfData = window.URL.createObjectURL(blob)
this.agreementUrl = encodeURIComponent(pdfData)
},
fail: err => {
console.log(err)
}
});
uni.navigateTo({
url: '/pages/mob/agreement/filePreview?url=' + this.agreementUrl;
})
推荐另外一种方式: 不做文档流转 blob,而是将读取文档流改成在线 pdf 地址的方式获取,这里需要后端提供 pdf 在线预览 url。需要注意在线 url 的可用性,如何去判断是否可用最简单的方式去复制到浏览器查看。
store 模块
queryPDFDetail({
commit,
dispatch,
}, data) {
return new Promise((resolve, reject) => {
let xaccessToken = uni.getStorageSync('xaccessToken').replace(/\"/g, "");
const URI = 'http://103.135.199.33:8099/smart-admin-api/api/file/preview?id=' + data.id + '&x-access-token=' + xaccessToken;
uni.navigateTo({
url: '/pages/pdf/pdf?url=' + encodeURIComponent(URI)
})
})
}
// pdf 预览页面
pdf.vue
<template>
<view style="width: 100%;">
<web-view :src="allUrl"></web-view>
</view>
</template>
<script>
export default {
data() {
return {
viewerUrl: '/static/hybrid/html/web/viewer.html',
allUrl: '',
}
},
onLoad (option) {
this.allUrl = this.viewerUrl + '?file=' + encodeURIComponent(option.url);
},
created() {
}
}
</script>
<style>
</style>
注意事项: 如果使用的 pdf 出现跨域问题,记得在 viewerjs 中将以下代码片段进行注释
try {
var viewerOrigin = new URL(window.location.href).origin || 'null';
if (HOSTED_VIEWER_ORIGINS.indexOf(viewerOrigin) >= 0) {
return;
}
var fileOrigin = new URL(file, window.location.href).origin;
//跨域请求错误提示
//if (fileOrigin !== viewerOrigin) {
//throw new Error('file origin does not match viewer\'s');
//}
} catch (ex) {
var message = ex && ex.message;
PDFViewerApplication.l10n.get('loading_error', null, 'An error occurred while loading the PDF.').then(function (loadingErrorMessage) {
PDFViewerApplication.error(loadingErrorMessage, { message: message });
});
throw ex;
}
下载
在 android 和 ios 上文件存储路径略有不同。
uni.downloadFile({
url: 'http://XXXXXXXXXXX',//下载地址接口返回
success: (data) => {
if (data.statusCode === 200) {
//文件保存到本地
uni.saveFile({
tempFilePath: data.tempFilePath, //临时路径
success: function(res) {
// 判断手机平台是 Android 还是 IOS
if (uni.getSystemInfoSync().platform === 'android') {
uni.showModal({
title:"保存地址为:",
content: "/Android/data/io.dcloud.HBuilder/apps/HBuilder/doc/uniapp_save",
duration: 3000,
})
} else {
uni.showModal({
icon: 'none',
title: '文件已保存:',
content: res.savedFilePath,
duration: 3000,
});
}
setTimeout(() => {
//打开文档查看
uni.openDocument({
filePath: res.savedFilePath,
success: function(res) {
// console.log('打开文档成功');
}
});
}, 3000)
}
});
}
},
fail: (err) => {
console.log(err);
uni.showToast({
icon: 'none',
mask: true,
title: '失败请重新下载',
});
},
});
上传
插件安装
在工具栏->插件安装->安装新插件->前往插件市场安装->搜索附件选择上传下载APP-H5-小程序。
uploadFileFn() {
let xaccessToken = uni.getStorageSync('xaccessToken').replace(/\"/g, "");
/**
* currentWebview: 当前webview
* url:上传接口地址
* name:附件key,服务端根据key值获取文件流,默认file,上传文件的key
* header: 上传接口请求头
*/
this.$refs.lFile.upload({
// #ifdef APP-PLUS
//(app端必传)nvue页面使用时请查阅nvue获取当前webview的api,当前示例为vue窗口
currentWebview: this.$mp.page.$getAppWebview(),
// #endif
//替换为你的上传接口地址
url: 'http://103.135.199.33:8099/smart-admin-api/api/file/localUpload/4',
// 服务端接收附件的key
name: 'file',
//根据你接口需求自定义 (优先不传content-type,安卓端无法收到参数再传)
header: {
'x-access-token': xaccessToken, //自定义请求头信息
// 'Access-Control-Allow-Methods':'POST'
},
// 限制选择附件的大小上限,默认10M
// maxSize: 20,
// 若需要在body单独添加附件名或附件大小如下方式传入组件:
// addName: '后端要的附件名称字段key,此处请勿写name的同值如(file),会覆盖name',
// addSize: '后端要的附件大小字段key'
// body参数直接写key,value,如:
// date: '2020-1-1',
// key2: 'value2',
});
}