uniapp 常用功能(文件下载加查看)

// 文件下载加查看
export function saveAndShowFile(typeName, val) {
    const imgFormat = /\.(jpg|jpeg|png|gif)$/; //图片格式匹配
    const documentFormatRegex = /\.(doc|docx|xls|xlsx|ppt|txt|pdf)$/i; //文件格式
    if (imgFormat.test(typeName)) {
        this.imageurl = val
        this.$refs.popup.open('center')
    } else if (documentFormatRegex.test(typeName)) {
        //文件预览功能微信预览需要先下载
        uni.downloadFile({
            url: val,
            success: function(res) {
                // uni.hideLoading();
                var filePath = res.tempFilePath;
                //文件保存到本地
                uni.saveFile({
                    tempFilePath:filePath, //临时路径
                    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('打开文档成功');
                                }
                            });
                        }, 1000)
                    }
                });
            },
            fail: function(err) {
                uni.hideLoading();
            }
        });
    } else {
        this.$modal.msg("该格式无法打开")
    }
}

 

posted on 2024-06-27 14:31  小虾米吖~  阅读(1)  评论(0编辑  收藏  举报