uniapp下载文件保存到手机本地

这篇内容讲述了在iOS和Android设备上遇到的文件下载问题,包括iPhone无法保存文件到本地,Android文件保存位置难以查找以及文件以时间戳命名。作者提供了相应的解决代码,通过uni-app进行文件下载管理,针对图片和视频保存到相册,以及非图片和视频文件的本地存储。对于Android设备,代码实现了在特定文件夹下保存并重命名文件,而iOS设备则提示用户手动保存。
摘要由CSDN通过智能技术生成

最近接到一个项目需求,下载各种格式文件保存到手机本地

遇到的问题如下:

1、iphone手机无法保存到文件中

2、Android手机文件保存的位置不易查找

3、Android手机文件存储名称非文件原名,而是以时间戳命名

不可抗因素:

 1、iphone自带的文件管理功能不能自动扫描各个APP下载的文件,需要手动保存一次才可以在文件管理器中找到

2、小程序对下载文件不友好,图片、视频可以正常下载到相册。其他格式文件Android手机只能下载其规定的文件夹中,iphone手机下载后无法无法保存

解决方法:

直接上代码

<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>

  • 14
    点赞
  • 99
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
UniApp H5可以通过以下方法保存图片到本地: 1. 使用HTML5的canvas将图片绘制到画布上,然后使用canvas.toDataURL()方法将画布内容转换为base64编码的字符串,最后使用FileSaver.js将字符串保存为图片文件。 代码示例: ``` // 获取图片 let img = new Image() img.src = 'https://example.com/image.jpg' // 将图片绘制到画布上 let canvas = document.createElement('canvas') canvas.width = img.width canvas.height = img.height let ctx = canvas.getContext('2d') ctx.drawImage(img, 0, 0) // 将画布内容转换为base64编码的字符串 let dataURL = canvas.toDataURL() // 保存为图片文件 let blob = dataURLtoBlob(dataURL) saveAs(blob, 'image.jpg') // 将base64编码的字符串转换为Blob对象 function dataURLtoBlob(dataURL) { let arr = dataURL.split(',') let mime = arr[0].match(/:(.*?);/)[1] let bstr = atob(arr[1]) let n = bstr.length let u8arr = new Uint8Array(n) while (n--) { u8arr[n] = bstr.charCodeAt(n) } return new Blob([u8arr], { type: mime }) } ``` 2. 使用HTML5的download属性,在a标签上设置download属性和href属性,href属性则为图片的链接,当用户点击a标签时,浏览器会自动下载图片文件到本地。 代码示例: ``` // 获取图片 let img = new Image() img.src = 'https://example.com/image.jpg' // 创建a标签 let a = document.createElement('a') a.href = img.src a.download = 'image.jpg' document.body.appendChild(a) // 模拟用户点击a标签 a.click() // 移除a标签 document.body.removeChild(a) ``` 以上两种方法都可以将图片保存到本地,可以根据实际需求选择适合自己的方法。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值