微信小程序的文件下载和预览

这里我使用了uniapp官方apiuni.downloadFileuni.openDocument

     // #ifdef MP-WEIXIN
        // 下载
		uni.downloadFile({
			//url: this.burl, //后端返回的文件地址
			url: 'xxxx.pdf',
			filePath: wx.env.USER_DATA_PATH + '/xxx.pdf',
			success: function(res) {
				if (res.statusCode === 200) {
					// 打开预览文件
					uni.openDocument({
						showMenu: true,// 右上角菜单,可以进行分享保存pdf
						filePath: res.filePath,
						success: function(res) {
							console.log(res, 'success')
						},
						fail: (err) => {
							uni.showToast({
								title: 'error',
								icon: 'none'
							})
						}
					})
				} else {
					uni.showToast({
						title: 'error',
						icon: 'none'
					})
				}
				uni.hideLoading()
				uni.showToast({
					title: 'success',
					icon: "success"
				})
			},
			fail: (err) => {
				uni.hideLoading()
				uni.showToast({
					title: 'error',
					icon: "error"
				})
			}
		})
		// #endif

APP

APP使用了uniapp官方apiuni.downloadFileuni.saveImageToPhotosAlbum(OBJECT)还有 uni.openDocument

// #ifdef APP-PLUS
      uni.downloadFile({
        url:
          "https://xxxx.pdf",
        success: res => {
          console.log(res)
          if (res.statusCode === 200) {
	        let _this=this
	        let eno=uni.getSystemInfoSync().platform //当前环境
	        let tempFile=res.tempFilePath
	        if(eno==='ios'){
	        	// 因为使用uni.saveFile保存文件时,安卓正常保存,并打开,ios一直报错
	        	//因为文件名用中文命名导致的,可以进行转码,不过需要注意的是只要在ios环境下转就行了,否则安卓无法下载
	        	tempFile=escape(tempFile)
	        }
            // 保存pdf文件至手机,一般安卓端存储路径为:手机存储/dcim/camera文件夹下
            // 直接调用的保存图片到系统相册的api
            uni.saveImageToPhotosAlbum({
              filePath: tempFile,
              success: function() {
                uni.showToast({
                  title: "文件已保存至/DCIM/CAMERA文件夹下",
                  icon: "none"
                })
                setTimeout(function() {
                  // 预览pdf文件
                  uni.openDocument({
                    filePath: res.tempFilePath,
                    showMenu: true,
                    success: function(file) {
                      console.log("file-success", file)
                    }
                  })
                }, 1500)
              },
              fail: function() {
                uni.showToast({
                  title: "保存失败,请稍后重试!",
                  icon: "none"
                })
              }
            })
          }
        }
      })
      // #endif

H5

H5的方法比较简单可以直接使用window.open方法下载。即:

window.open("xxxx.pdf")

如果你的浏览器支持预览,就会自动打开预览文件,然后自己手动下载文件,不支持则会直接下载。
但是在ios系统里,有时会出现window.open方法失效的问题。明明后端返回了地址,但是使用window.open却没有动静。这是因为safari浏览器有一些安全策略,禁止在回调函数中执行window.open方法,以防页面不断弹出窗口。
所以,为了解决这种问题,可以先打开一个空白页,然后在更新它的地址

// #ifdef H5
// 打开空白页
const winRef = window.open("about:blank","_blank");
// 通过接口到后台获取文件地址,然后更新空白页地址
api(parm).then(url=>{
winRef.location=url
})
// #endif
Logo

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

更多推荐