实际记录uni-app使用uni-download和uni.saveFile下载保存文件遇到的问题以及解决方法

项目场景:

app里的开发的小程序需要下载文件功能以及一个下载中心页面可以查看所有下载的文件,使用了uni.download下载以及uni.saveFile保存文件
下载中心页面实现逻辑
1.下载文件后保存文件名和uni.saveFile返回的路径uni.setStorageSync到缓存里

uni.downloadFile({
    
    
					    method: 'GET',
					    url: 你的url,
					    timeout: 5000,
					   header:{
    
    
					     authorization: 你的token,
					   },
					    success: (data) => {
    
    
							//接口返回的文件流
							console.log("fileData",data)
					            if (data.statusCode === 200) {
    
    
					                    //文件保存到本地
					                    uni.saveFile({
    
    
					                            tempFilePath: data.tempFilePath, //临时路径
					                            success: function(res) {
    
    
					                                console.log("data.",res)
														let list = uni.getStorageSync("__local_down_history");
														if (list.length) {
    
    
															let arrNew=list
															let newObj={
    
    
																path:res.savedFilePath,
																name:fundcode+"_"+fundNo+'.'+fileType
															}
															arrNew.unshift(newObj);
															_this.localSearchList=arrNew
															// arrUnique(this.localSearchList);
														} else {
    
    
															_this.localSearchList = [{
    
    
																path:res.savedFilePath,
																name:fundcode+"_"+fundNo+'.'+fileType
															}];
														}
														console.log("文件缓存",_this.localSearchList)
														uni.setStorageSync("__local_down_history", _this.localSearchList);        
					                            }
					                    });
										
					            }
					    },
					    fail: (err) => {
    
    
					            console.log(err);
					            // uni.showToast({
    
    
					            //         icon: 'none',
					            //         mask: true,
					            //         title: '失败请重新下载',
					            // });
					    },
					})

2.下载中心读取uni.getStorageSync缓存的文件列表

<ourLoading isFullScreen :active='loadingStatus' text="加载中..." color='rgb(0, 106, 254)' textColor='rgb(0, 106, 254)'	 />
<uni-list class="uni-list" :border="false" style="margin-bottom: 50px;">
				<!-- 列表渲染 -->
				<uni-list-item v-for="(item,index) in currnetArr" :key="index" >
					<template v-slot:body>
						<view class="main">
							<view class="mainContent"  >
							//节流打开文件
									<text class="author" style="color: #89939B;" @tap="$u.throttle(openURL(item.path), 1000)">{
    
    {
    
    item.name}}</text>
							</view>
								
						</view>
					</template>
				</uni-list-item>
			</uni-list>
data() {
    
    
			return {
    
    
				currnetArr:uni.getStorageSync(你保存的缓存key值),
				loadingStatus:false,
			}
openURL(path){
    
    
				console.log('path',path)
				const _this = this
				if(!this.loadingStatus) {
    
    
					this.loadingStatus = true
					setTimeout(() => {
    
    
						uni.openDocument({
    
    
								filePath: path,
								success: function(res) {
    
    
										_this.loadingStatus = false
										console.log('打开文档成功');
								},
								fail: function(e){
    
    
									_this.loadingStatus = false
									uni.showToast({
    
    
										icon: 'none',
										mask: true,
										title: '文件打开失败',
									});
								}
						});
					}, 1000)
				}
				
				
			},

问题描述

通过这种uni.downloadFile配合uni.saveFile下载并保存文件,然后在下载中心点击打开文件,逻辑是没问题的。但是这个方式苹果手机可以正常打开文件,安卓一直打开文件报错。


原因分析:

分析是download方法的问题,保存文件一般是内部复制,系统差异应该是保存路径的问题, 即uni.saveFile返回的savedFilePath保存的临时文件路径问题


解决方案:

配合H5+的下载方法,强行指定下载路径,这样就不会有临时路径的差异了,从而解决安卓系统打不开文件问题,下面是下载文件最终版本代码

uni.downloadFile({
    
    
					     method: 'GET',
					     url: 你的url,
					     timeout: 2000,
					    header:{
    
    
					      authorization:你的 token,
					    },
					     success: (data) => {
    
    
					             if (data.statusCode === 200) {
    
    
									 plus.io.resolveLocalFileSystemURL( data.tempFilePath, function( entry ) {
    
    
										 const name = `${
      
      entry.name}.pdf` //这里设置文件名根据自己的下载文件后缀来修改,我这边需求是pdf
										 entry.getParent(function(scb) {
    
    
											 entry.moveTo(scb,name, function(sEntry) {
    
    
												 //文件保存到本地
												uni.saveFile({
    
    
														tempFilePath: sEntry.fullPath, //临时路径
														success: function(res) {
    
    
																// 判断手机平台是 Android 还是 IOS
																if (uni.getSystemInfoSync().platform === 'android') {
    
    
																		uni.showModal({
    
    
																				title:"保存地址为:",
																				content: res.savedFilePath,
																				duration: 3000,
																		})
																} else {
    
    
																		uni.showModal({
    
    
																				icon: 'none',
																				title: '文件已保存:',
																				content: res.savedFilePath,
																				duration: 3000,
																		});
																}
																
																let list = uni.getStorageSync("__local_down_history");
																if (list.length) {
    
    
																	let arrNew=list
																	let newObj={
    
    
																		path:res.savedFilePath,
																		name:"收据."+ReceiptNo+'.pdf' 
																		//这里的保存的name是下载中心展示的文件名,不是这个文件原本的名字
																	}
																	arrNew.unshift(newObj);
																	_this.localSearchList=arrNew
																	// arrUnique(this.localSearchList);
																} else {
    
    
																	_this.localSearchList = [{
    
    
																		path:res.savedFilePath,
																		name:"收据."+ReceiptNo+'.pdf'
																	}];
																}
																console.log("文件缓存",_this.localSearchList)
																uni.setStorageSync("__local_down_history", _this.localSearchList);        
														}
												});
											 } )
										 })
									 })
					                     
					             }
					     },
					     fail: (err) => {
    
    
					             console.log(err);
					             uni.showToast({
    
    
					                     icon: 'none',
					                     mask: true,
					                     title: '失败请重新下载',
					             });
					     },
					 })

猜你喜欢

转载自blog.csdn.net/m0_55588706/article/details/128965974