uniapp 通用下载文件方法并可以重命名文件

该代码段展示了在uni-app中如何下载一个文件并将其保存到本地,然后打开文件。当下载成功(statusCode为200)时,会提示用户文件已保存,并使用uni.openDocument打开文件,支持转发到微信。如果下载失败,则显示错误信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

const	downloadPublic = (attachLink,fileType) => {
	let that = this
	let filePath = uni.env.USER_DATA_PATH+'/'+ decodeURIComponent(getFileNameByPath(attachLink))
	uni.downloadFile({
		url: attachLink , //下载地址,后端接口获取的链接
		success: (res) => {
			if (res.statusCode === 200) {
				uni.getFileSystemManager().saveFile({ //文件保存到本地
					tempFilePath: res.tempFilePath, //临时路径  data.tempFilePath
					filePath:filePath,
					success: function(res) {
						uni.showToast({
							icon: 'none',
							mask: true,
							title: '文件已保存!', 
							duration: 3000,
						});
						uni.openDocument({
							fileType: fileType,
							showMenu:true, //关键点,可以转发到微信
							filePath: res.savedFilePath,
							success: function(res) {
								console.log('打开文档成功');
							}
						});
					}
				});
			}
		},
		fail: (err) => {
			console.log(err);
			uni.showToast({
				icon: 'none',
				mask: true,
				title: '失败请重新下载',
			});
		},
	});

}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值