uniapp,实现下载文件(uni.downloadFile),并保存到本地(uni.saveFile),打开文件预览(uni.openDocument)

<!-- #ifdef  APP-PLUS -->
<u-button class="btn" @click="Download">下载签订合同</u-button>
<!-- #endif -->

<!-- #ifdef  H5 -->
<a href="http://192.168.0.200:8058/files/200200711.doc" class="btn">下载签订合同</a>
<!-- #endif -->
//签订合同下载
Download() {
    uni.downloadFile({
        url: 'http://192.168.0.200:8058/files/200200711.doc',//下载地址接口返回
        success: (data) => {
            if (data.statusCode === 200) {
                //文件保存到本地
                uni.saveFile({
                    tempFilePath: data.tempFilePath, //临时路径
                    success: function(res) {
                        uni.showToast({
                            icon: 'none',
                            mask: true,
                            title: '文件已保存:' + res.savedFilePath, //保存路径
                            duration: 3000,
                        });
                        setTimeout(() => {
                            //打开文档查看
                            uni.openDocument({
                                filePath: res.savedFilePath,
                                success: function(res) {
                                    // console.log('打开文档成功');
                                }
                            });
                        }, 3000)
                    }
                });
            }
        },
        fail: (err) => {
            console.log(err);
            uni.showToast({
                icon: 'none',
                mask: true,
                title: '失败请重新下载',
            });
        },
    });
},

https://blog.csdn.net/qq_40745143/article/details/107287300

posted @ 2022-08-10 14:44  奔向太阳的向日葵  阅读(8135)  评论(0编辑  收藏  举报