uniapp微信小程序下载文件,保存文件功能总结

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

先使用下载文件api把文件下载下来,再使用wx.openDocument() 打开文件里面加上showMenu字段,然后就可以看到在打开的文件右上角出现了···,就可以转发了
在这里插入图片描述
转载 https://blog.csdn.net/qq_37131884/article/details/123360114

### UniApp 微信小程序 文件上传实现方法 #### 配置环境与准备 为了实现在UniApp中进行微信小程序文件上传,需确保项目已正确配置并连接至微信开发者平台。这包括但不限于完成应用基本信息设置以及获取必要的API权限。 #### 初始化参数设定 在页面数据对象内定义用于存储图片路径列表和其他控制变量: ```javascript data() { return { imgList: [], // 图片选择后的本地临时地址集合 uploadIndex: 0, uploadImgLength: 0, uploadList: [] } } ``` 上述代码片段展示了初始化所需的关键属性[^3]。 #### 处理用户选取照片事件 当用户点击按钮选择要上传的照片时,触发`chooseImage`函数来打开相册或相机界面供用户挑选图像资源,并将选中的图片加入到`imgList`数组里保存起来等待后续处理。 ```javascript methods: { chooseImage(e) { let that = this; uni.chooseImage({ count: 9, // 默认最多可以选择几张图片 sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType: ['album', 'camera'], // 获取图片的方式(从相册/拍照) success(res) { const tempFilePaths = res.tempFilePaths; that.imgList.push(...tempFilePaths); console.log('当前图片:',that.imgList); }, fail(err){ console.error("选择失败",err); } }); } } ``` 此部分逻辑实现了让用户能够方便快捷地添加待上传的多媒体素材到应用程序当中。 #### 执行实际上传操作 一旦确认好所有想要发送给服务器端的数据之后就可以调用`uploadFile` API 来发起HTTP POST请求并将选定好的文件作为表单的一部分提交出去,在这里需要注意的是每次只能单独传送一个文件所以可能需要用到循环结构依次遍历整个队列直至全部完成为止。 ```javascript async function doUpload(){ try{ while(this.uploadIndex<this.imgList.length){ await new Promise((resolve,reject)=>{ uni.uploadFile({ url:'https://example.com/upload',// 替换成自己的服务端URL filePath:this.imgList[this.uploadIndex], name:'file', formData:{'user':'test'}, success(uploadRes){ resolve(); }, fail(error){ reject(error); } }) }).then(()=>{ ++this.uploadIndex; }).catch(console.warn); } console.info(`总共${this.imgList.length}张图片已经成功上传`); } catch (e){ console.error("发生错误:", e.message); } } ``` 这段异步函数负责管理批量上传流程并且提供了简单的进度跟踪机制以便于监控任务状态变化情况。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值