最近写的uniapp项目需要新增一个pdf下载和打开查看功能,摸索了半天终于写了出来,现分享出来供有需要的同行参考,欢迎指正

async function DownloadSignature() {
        //请求后端接口,返回值为一个url地址
		let res=await req.flow.flowDownload(data.flowId)
		uni.downloadFile({
            //res.data就是返回的地址
			url: res.data,
			success: function (res) {
				if (res.statusCode === 200) {
					// 下载成功
					const filePath = res.tempFilePath; // 下载后的临时文件路径
					uni.saveFile({
						tempFilePath: filePath,
						success: function (listRes) {
                            //此API是为了拿到文件保存的详细路径
							plus.io.requestFileSystem( plus.io.PRIVATE_DOC, function( fs ) {  
								// 拿到 _doc 所在的完整路径  
								console.log(fs.root.fullPath);  
                                //弹出文件保存路径
								http.hint('文件保存成功'+fs.root.fullPath+listRes.savedFilePath,3000)
							}, function ( e ) {  
								console.log( "Request file system failed: " + e.message );  
							} );
                            //保存成功后,调用文件打开方法
							uni.openDocument({
								filePath,
								success: function(file) {
									console.log('file-success',file);
								}
							});
						},
						fail: function (err) {
						// 保存文件失败
							uni.showToast({
								title: '保存文件失败',
								icon: 'none'
							});
						}
					});
				} else {
					// 下载失败
					uni.showToast({
						title: '下载失败',
						icon: 'none'
					});
				}
			},
			fail: function (err) {
				// 下载请求失败
				uni.showToast({
					title: '下载请求失败',
					icon: 'none'
				});
			}
		});
	}

因为功能写的紧急,还没有摸索出文件重命名方法(因为下载后的文件名是时间戳,这属于优化的一部分)以及自定义文件保存路径方法,

效果图:

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐