小程序文件下载并查看

3,431 阅读1分钟

实例:图片、文件下载并查看

下载 wx.downloadFile

// downPath:下载资源的 url
// type:文件类型
downloadFile(downPath, type) {
    let header = {
        // 请求头
    }
    let _this = this
    let downloadTask = wx.downloadFile({
        url: downPath,
        header: header,
        success({errMsg, statusCode, tempFilePath}) {
            // tempFilePath: 临时文件路径 (本地路径)
            // statusCode: 开发者服务器返回的 HTTP 状态码
            if (statusCode === 200) {
                // 预览
                _this.previewImg(tempFilePath, type)
            } else {
                wx.showToast({
                    title: errMsg, icon: 'none', duration: 3e3
                })
            }
        },
        fail: () => {},
        complete: () => {}
    })

    // 下载进度监听
    downloadTask.onProgressUpdate(({progress}) => {
      console.log(progress)
    })
}

图片预览wx.previewImage、 文件预览wx.openDocument

previewImg(tempFilePath, type){
    // 判断是否是图片
    let imgType = ['png', 'jpg', 'jpeg']
    let isImg = imgType.indexOf(type) >= 0 ? true : false
    
    if ( isImg ) {
        // 打开图片
        wx.previewImage({
            current: tempFilePath
            urls: [tempFilePath], // 支持多张预览
            complete: () => {}
        })
    } else {
        // 打开文件
       wx.openDocument({
            // 文件路径 (本地路径)
            filePath: tempFilePath,
            // 支持文件类型:doc、docx、xls、xlsx、ppt、pptx、pdf
            fileType: type,  
            success: () => {},
            fail: ({errMsg = '打开文件失败,请稍后再试!'} = {}) => {
                wx.showToast({
                    title: errMsg, icon: 'none', duration: 3e3
                })
            }
        })
    }
}

微信官方文档地址:

下载:wx.downloadFile

监听下载进度变化事件

图片预览:wx.previewImage

文件预览:wx.openDocument