uni-APP,微信小程序,保存日志文件为txt文件,然后转发给微信好友

1、获取全局唯一的文件管理器

	const fileManager = wx.getFileSystemManager();

2、保存日志文件内容为txt文件

getTxtFileToShare() {
				let json = {
					"a": '1234567890',
					'b': '测试中文内容'
				}
				//将数据转换为字符串
				let jsonString = JSON.stringify(json);
				let that = this;
				// 将字符串保存为txt文件
				fileManager.writeFile({
					filePath: wx.env.USER_DATA_PATH + '/data.txt',
					data: jsonString,
					encoding: 'utf-8',
					success(res) {
						console.log('文件保存成功:', res);
						//that.filePath = wx.env.USER_DATA_PATH + '/data.txt';
						let localFilePath =  wx.env.USER_DATA_PATH + '/data.txt';
						that.uploadFileToOss(localFilePath);

					},
					fail: function(res) {
						console.error('文件保存失败:', res);
					}
				});

			},

3、上传到OSS

//上传文件到oss
			async uploadFileToOss(localFilePath){
				let data = await this.initClient();
				const host = 'xxxxx';
				const signature = data.signature;
				const ossAccessKeyId = data.OSSAccessKeyId;
				const policy = data.policy;
				const securityToken = data.securityToken;
				let date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let month2 = month < 10 ? "0" + month : month;
				let date2 = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
				let tenantId = getStoreSyncUtil('userInfo').tenant_id;
				let uuid = util.guid()
				const key =
					`public/meter-read-robot/upload/packet/${tenantId}/${year}/${month2}/${date2}/${uuid}.txt`;
				//const key = '/public/car/000000/2023/01/12/'+res.tempFiles[0].name;  //报错多了一根斜杠报错:InvalidObjectName
				let uploadTask = uni.uploadFile({
					url: host, // 开发者服务器的URL。
					filePath: localFilePath, // 待上传文件的文件路径。
					name: 'file', // 必须填file。
					formData: {
						key,
						policy,
						'success_action_status': '200', //让服务端返回200,不然,默认会返回204
						OSSAccessKeyId: ossAccessKeyId,
						signature,
						'x-oss-security-token': securityToken // 使用STS签名时必传。
					},
					success: (res2) => {
						console.log('上传成功',res2)
						
						if (res2.statusCode === 200) {
							let link = host + "/" + key;
							this.filePath = link;
						}
					},
					fail: err => {
						console.log(err);
					},
					complete: function() {
					}
				});
			},

4、下载文件并完成分享

shareFile() {
				// callback 写法
				if(filePath == '') return;
				wx.downloadFile({
					url: this.filePath, // 下载url
					success(res) {
						console.log('res-downloadFile-成功', res)
						// 下载完成后转发
						wx.shareFileMessage({
							filePath: res.tempFilePath,
							success(res) {
								console.log('shareFileMessage成功', res)
							},
							fail(res) {
								console.log('shareFileMessage失败', res)
							},
						})
					},
					fail(res) {
						console.log('res-downloadFile-失败', res)
					},
				})
			},

你可能感兴趣的:(uni-app,微信小程序,微信)