The uniapp download file is saved locally on the phone

Recently received a project request, download files in various formats and save them locally on the phone

The problems encountered are as follows:

1. The iPhone cannot be saved to the file

2. The location where Android phone files are saved is not easy to find

3. The file storage name of the Android mobile phone is not the original name of the file, but is named after the timestamp

Majeure:

 1. The built-in file management function of the iPhone cannot automatically scan the files downloaded by each APP. It needs to be manually saved once before it can be found in the file manager.

2. The applet is not friendly to downloading files, and pictures and videos can be downloaded to the album normally. Android mobile phones can only download files in other formats in their specified folders, and iPhone mobile phones cannot save them after downloading

Solution:

directly on the code

<template>
    <view>
        <view class="linView">
			<view class="load-progress" :class="loadProgress!=0?'show':'hide'" :style="[{top:CustomBar+'px'}]">
				<view class="load-progress-bar bg-green" :style="[{transform: 'translate3d(-' + (100-loadProgress) + '%, 0px, 0px)'}]"></view>
				<view class="load-progress-spinner text-green"></view>
				<view class="dltDownLv">
					<view>正在为您下载</view>
					<view class="dltDownLvNew">{
   
   {dltDownLvNew}}</view>
					<view>/</view>
					<view>{
   
   {dltDownLvAll}}</view>
					<view class="dltDownLvWc">已完成:</view>
					<view>{
   
   {dltDownLvWc}}</view>
				</view>
			</view>
		</view>
        <view @tap="clickPeople('下载地址')">下载</view>
    
    </view>
   
</template>

<script>
    export default{
        data(){
            return{
                loadProgress: 0,//加载index
				CustomBar: this.CustomBar,
                dltDownLvNew:"",//已下载
				dltDownLvAll:"",//总长度
				dltDownLvWc:"",//完成率
                downloadUlr:"",//下载地址
				suffix:"",//文件后缀
            }
        },
        methods:{
            clickPeople(e){//点击下载
				let _this = this;
                //下载地址
				this.downloadUlr = e; 
                //获取地址后缀
				this.suffix = e.split(".")[e.split(".").length - 1];
				
                //判断是否为(图片或视频)
				if(e.substring(e.length - 3) == "MP4" || e.substring(e.length - 3) == "mp4" || e.substring(e.length - 3) == "jpg" || e.substring(e.length - 3) == "png"){
					
					const downloadTask = uni.downloadFile({
						url:e, 
						success: res => {
							if (res.statusCode === 200) {
								
								if(res.tempFilePath.substring(res.tempFilePath.length - 3) == "mp4" || res.tempFilePath.substring(res.tempFilePath.length - 3) == "MP4"){//视频
								    //保存视频到相册
									uni.saveVideoToPhotosAlbum({
										filePath: res.tempFilePath,
										success: function () {
											
											uni.showToast({
												title: '保存成功',
												icon: 'none',
												duration:2000,
												mask:true
											});
										},
										fail: function() {
											this.loadProgress = 0;
											uni.showToast({
												title: '保存失败',
												icon: 'none'
											});
										}
									});
								}else{//图片
									// 图片保存到手机相册
									uni.saveImageToPhotosAlbum({
										filePath: res.tempFilePath,
										success: function() {
											uni.showToast({
												title: '保存成功',
												icon: 'none',
												duration:2000,
												mask:true
											});
										},
										fail: function() {
											
											this.loadProgress = 0;
											uni.showToast({
												title: '保存失败',
												icon: 'none'
											});
										}
									});
								
								}
								
							}else{
								uni.showToast({
									title:'下载失败',
									icon:"none"
								})
							}
						},
						fail:(err) => {
							
							this.loadProgress = 0;
							uni.showToast({
								icon:"none",
								mask:true,
								title:'下载失败'
							})
						}
					});
					downloadTask.onProgressUpdate((res) => {
						this.loadProgress = res.progress;
						if (this.loadProgress < 100) {
							
						} else {
							this.loadProgress = 0;
						}
						if(res.totalBytesExpectedToWrite < 10485760){
							this.dltDownLvNew = Math.ceil(res.totalBytesWritten / 1024) + "KB";
							this.dltDownLvAll = Math.ceil(res.totalBytesExpectedToWrite / 1024) + "KB";
							this.dltDownLvWc = res.progress + "%"
						}else{
							this.dltDownLvNew = Math.ceil(res.totalBytesWritten / 1048576) + "M"
							this.dltDownLvAll = Math.ceil(res.totalBytesExpectedToWrite / 1048576) + "M";
							this.dltDownLvWc = res.progress + "%"
						}
					});
				}else{
                    //下载文件为非图片和视频的文件
					let _this = this;
					
					const downloadTaskt = uni.downloadFile({
						url:e,//下载地址接口返回
						success:(data) => {
							uni.hideLoading()
							if(data.statusCode === 200){
								var sFilePath = data.tempFilePath
								var sFileName = _this.downloadUlr.split('/')[_this.downloadUlr.split('/').length - 1];//原来的文件名
								
								//#ifdef APP-PLUS
									//文件保存到本地
									uni.saveFile({
										tempFilePath: data.tempFilePath,//临时路径
										success:function(res){
											
											var savedFilePath = res.savedFilePath;
											let osname = plus.os.name;
                                            //ios手机直接打开文件,手动存储文件到手机,Android手机从根目录创建文件夹,保存文件并改名
											if (osname == 'Android') {
												uni.showToast({
													icon:'none',
													mask:true, 
													title:'保存成功',
													duration:1000,
												});
												_this.fSetFileName(res.savedFilePath, sFilePath);
											}
											setTimeout(() => {
												//打开文档查看
												uni.openDocument({
													filePath:res.savedFilePath,
													success:function(res){
														// console.log("成功打开文件")
													},
													fail(){
														// console.log("打开文件失败")
													}
												})
											},1000)
										},
										fail:function(res){
											
										}
									});
								//#endif
								//#ifdef MP-WEIXIN
                                    //小程序对文件下载并不友好,不建议使用小程序当做下载器
									const FileSystemManager = wx.getFileSystemManager();
									FileSystemManager.saveFile({//下载成功后保存到本地
										tempFilePath:data.tempFilePath,
										filePath:wx.env.USER_DATA_PATH + "/" + sFileName,
										success(res2){
											if(res2.errMsg == 'saveFile:ok'){
												
												// 判断手机平台是 Android 还是 IOS
												if (uni.getSystemInfoSync().platform === 'android') {
													// console.log('运行Android上')
													uni.showModal({
														title:"保存地址为",
														content:"手机存储/Android/data/com.tencent.mm/MicroMsg/wxanewfiles"
													})
												} else {
													// console.log('运行iOS上')
													uni.showToast({
														title:"请转移APP下载",
														icon:"none"
													})
												}
												
											}else{
												uni.showToast({
													title:"下载失败",
													icon:"none"
												})
											}
										},
										fail(){
											uni.showToast({
												title:"下载失败",
												icon:"none"
											})
										}
									})
								//#endif
								
							}else{
								this.loadProgress = 0;
								uni.showToast({
									icon:"none",
									mask:true,
									title:"下载失败"
								})
							}
						},
						fail:(err) => {
							this.arcZzShow = false;
							this.loadProgress = 0;
							uni.showToast({
								icon:"none",
								mask:true,
								title:"下载失败"
							})
						}
					})
					downloadTaskt.onProgressUpdate((res) => {
						this.loadProgress = res.progress;
						if (this.loadProgress < 100) {
							
						} else {
							this.loadProgress = 0;
						}
						if(res.totalBytesExpectedToWrite < 10485760){
							this.dltDownLvNew = Math.ceil(res.totalBytesWritten / 1024) + "KB";
							this.dltDownLvAll = Math.ceil(res.totalBytesExpectedToWrite / 1024) + "KB";
							this.dltDownLvWc = res.progress + "%"
						}else{
							this.dltDownLvNew = Math.ceil(res.totalBytesWritten / 1048576) + "M"
							this.dltDownLvAll = Math.ceil(res.totalBytesExpectedToWrite / 1048576) + "M";
							this.dltDownLvWc = res.progress + "%"
						}
						
					});
				}
	
					
			},//点击下载END
			// 给下载的文件重命名
			fSetFileName(sFilePath, sFileName) {
				var sFileName = sFileName.split('/')[sFileName.split('/').length - 1];//原来的文件名
				
				var aFileUrl = sFilePath.split('/').splice(0, sFilePath.split('/').length - 1);//saveFile API保存的本地地址
				
				var url = this.downloadUlr;//下载地址
					// 'url下载地址(和上面的一样)'
				let dtask = plus.downloader.createDownload(url, {
						filename: "file://storage/emulated/0/AAA/" + sFileName //在手机存储更目录创建一个叫AAA的文件夹,把文件存储进去,并更改会原名
					},
					(d, status) => {
						if (status == 200) {
							let fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename);
							
						} else {
							//下载失败
							plus.downloader.clear(); //清除下载任务
						}
					})
				dtask.start();
			}
			 
        }

    }

</script>
<style>
    .load-progress {
	    pointer-events: none;
	    top: 0;
	    position: absolute;
	    width: 100%;
	    left: 0;
	    z-index: 2000;
	}
	.load-progress.hide {
	    display: none;
	}
	.load-progress .load-progress-bar {
	    position: relative;
	    width: 100%;
	    height: 2px;
	    overflow: hidden;
	    -webkit-transition: all 200ms ease 0s;
	    transition: all 200ms ease 0s;
	}
	.bg-green {
	    background-color: #ff692d;
	    color: #ffffff;
	}
	.load-progress .load-progress-spinner {
	    position: absolute;
	    top: 5px;
	    right: 5px;
	    z-index: 2000;
	    display: block;
	}
	.text-green, .line-green, .lines-green {
    color: #ff692d;
	}
</style>

Guess you like

Origin blog.csdn.net/fbqgdxw/article/details/124293782