关于 uniapp 的文件下载和预览,downloadFile & openDocument

这个破问题搞得我很难受,由于项目我是后来加入的,之前开发人员传入的filePath不是一个具体的文件地址,也不知什么原因导致下载不了也预览不了。

直接代码

let fileType = “PNG”;//文件类型
let filePath = "这里是需要下载的文件具体网络地址";
uni.showLoading({
		title: '文件下载中'
});
if(fileType){ 
		fileType = fileType.toLowerCase();
}
//先下载文件
uni.downloadFile({
					url: encodeURI(filePath),//注意中文文件名的网络地址需要encodeURI
					success(res) {  
						uni.hideLoading();
						//预览图片或打开文件
						if(fileType == "png" || fileType == "jpg" || fileType == "jpeg"){
						    // 图片的话直接预览
							uni.previewImage({
								urls: [res.tempFilePath]
							});
							uni.hideLoading();
						}else{
							uni.openDocument({
								filePath: res.tempFilePath,
								success() {
								},
								fail(e) {
									uni.hideLoading();
									uni.showToast({
										icon: 'none',
										title: '文件打开失败!'
									});
								}
							});
						}
					},
					fail() {
						uni.hideLoading();
						uni.showToast({
							icon: 'none',
							title: '下载出错!'
						});
					},
					complete() {
						uni.hideLoading();
					}
				});

最重要的这个还是要看 需要下载的文件地址是否存在。还有要具体的文件地址。必须是小程序已经设置名单的域名下的文件才行。

以下是一个基于uni-app的文件预览代码示例: ```html <template> <view> <uni-list> <uni-list-item v-for="(item, index) in fileList" :key="index" :title="item.name" :extra="item.size + 'KB'" @click="previewFile(item)"> <uni-icon :type="getFileIcon(item.type)"></uni-icon> </uni-list-item> </uni-list> </view> </template> <script> export default { data() { return { fileList: [ { name: 'test.pdf', size: 1024, type: 'pdf', url: 'http://example.com/test.pdf' }, { name: 'test.doc', size: 2048, type: 'doc', url: 'http://example.com/test.doc' }, { name: 'test.jpg', size: 3072, type: 'jpg', url: 'http://example.com/test.jpg' } ] } }, methods: { previewFile(file) { uni.showLoading({ title: '加载中...' }) uni.downloadFile({ url: file.url, success: function (res) { uni.hideLoading() if (res.statusCode === 200) { uni.openDocument({ filePath: res.tempFilePath }) } }, fail: function () { uni.hideLoading() uni.showToast({ title: '预览失败', icon: 'none' }) } }) }, getFileIcon(fileType) { switch (fileType) { case 'pdf': return 'pdf' case 'doc': return 'doc' case 'jpg': return 'camera' default: return 'file' } } } } </script> ``` 该示例中,使用uni-listuni-list-item组件展示文件列表,并通过@click事件监听文件项的点击,调用previewFile方法进行文件预览。 在previewFile方法中,使用uni.downloadFile下载文件,并在下载成功后通过uni.openDocument打开文件。在下载过程中,通过uni.showLoading展示加载中提示,下载完成后通过uni.hideLoading隐藏提示。若下载失败,则通过uni.showToast展示预览失败提示。 getFileIcon方法用于根据文件类型返回对应的图标类型,以便在文件列表中展示文件图标。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值