微信小程序原生下载文件流

487 阅读1分钟

预览文件流

previewFile() {
    wx.request({

    url: 'XXX/downContractFile',

    method: "get",

    responseType: "arraybuffer", //此处是请求文件流,必须带入的属性

    header: {

    "content-type": "application/json",

    Authorization: "Bearer " + wx.getStorageSync("token"),

    Cookie: "JSESSIONID=" + wx.getStorageSync("sessionID"),

    },

    success: rest => {

            const fs = wx.getFileSystemManager(); //获取全局唯一的文件管理器

            fs.writeFile({ // 写文件

            filePath: wx.env.USER_DATA_PATH + "/电子发票在线预览.pdf", // wx.env.USER_DATA_PATH 指定临时文件存入的路

            data: rest.data,

            encoding: "binary", //二进制流文件必须是 binary

            success(res) {

                wx.openDocument({ // 新开页面打开文档

                filePath: wx.env.USER_DATA_PATH + "/电子发票在线预览.pdf", //拿上面存入的文件路径

                fileType: 'pdf',

                showMenu: true,

                success: function (res) {

                    setTimeout(() => {

                        wx.hideLoading()

                        }, 500)

                }
            })
        }
    })
    }
    })
}

下载文件流 1、获取文件流

downFile() {

    let that = this;

    wx.downloadFile({

    url: `${common.config.downContractFile}`,

    responseType: "arraybuffer", //此处是请求文件流,必须带入的属性

    header: {

    "content-type": "application/pdf",

    Authorization: "Bearer " + wx.getStorageSync("token"),

    Cookie: "JSESSIONID=" + wx.getStorageSync("sessionID"),

    },

    success: async function (res) {

        if (res.statusCode === 200) {
         //读取文件流
        let readRes = await that.getReadRes(res)
         //写入文件流
        let writeRes = await that.writeFileRes(readRes)

        }

    },

    fail: function (error) {

    console.error('下载失败', error);

    }

    });

}

读取文件流 getReadRes(res) {

return new Promise((resolve, reject) => {

const fs = wx.getFileSystemManager();

fs.readFile({

filePath: res.tempFilePath,

encoding: 'binary', // 读取为二进制格式

success(readRes) {

    resolve(readRes)

},

fail(err) {

reject('文件读取失败')

}

});

})

} 写入文件流

writeFileRes(readRes) {

    return new Promise((resolve, reject) => {

    const fs = wx.getFileSystemManager();

    fs.writeFile({ //

    filePath: wx.env.USER_DATA_PATH + "/电子发票在线预览.pdf", // wx.env.USER_DATA_PATH 指定临时文件存入的路

    data: readRes.data,

    encoding: "binary", //二进制流文件必须是 binary

    success(res) {

    resolve()

    }

    })

    })

}

转发下载文档

shareFileMessage(){

    wx.shareFileMessage({

    filePath: wx.env.USER_DATA_PATH + "/电子发票在线预览.pdf",

    fileName: '发票预览',

    success() {},

    fail: console.error,

    })
}