问题 如何在微信小程序中进行下载并预览文件呢
做项目时,会有这样的一个需求,能够下载并预览文件,如果想要直接利用第三方阅读软件(比如qq浏览器)打开的话,小程序暂时不能实现,但是小程序提供了在小程序中能够
下载并预览文件,使用到的API有wx.downloadFile()下载文件,wx.openDocument()打开文件
解决 1 下载预览单个文件
如果服务器端传过来的数据中,每个列表文件只有一个话,可以采取如下方法
1 wxml代码
<view wx:for="{{documentlist}}" wx:for-item="item" wx:key="id">
                <view class="content">
                    <view class="title">时间</view>
                    <view value="{{item.date}}">{{item.date}}</view>
                </view>
    <button  bindtap="downloadFile" data-index='{{item.id}}' data-url="{{item.filepath}}">下载文件并预览</button>
</view>1 js代码
在官方文档中 wx.openDocument()中的fileType不是必填项,但是在实际中,如果不填写文件类型会出现预览失败的情况。但是目前fileType文件类型仅支doc、docx、xls、xlsx、ppt、pptx、pdf这些格式
downloadFile: function(e) {
let that=this;
console.log(e);
let url = e.currentTarget.dataset.url;
//文件类型,截取url后缀
let type=url.substr(url.lastIndexOf('.')+1);
//提示文件下载
wx.showLoading({
    title: '文件下载中',
})
wx.downloadFile({
    url: url,
    header: {
        'content-type': 'application/json',
    },
    success: function(res) {
        var filePath = res.tempFilePath;
        console.log("临时路径"+filePath);
        //关闭加载图标
        wx.hideLoading();
            // 打开文件
            wx.openDocument({
                filePath: filePath,
                fileType: type, 
                success: function(res) {
                    console.log('打开文档成功');
                    console.log(res.data);
            },
            fail: function(res) {
            console.log(res);
            console.log('文件打开失败');
            wx.showToast({
                title: '文件打开失败',
                icon: 'none',
                duration: 2000
            })
        },
        complete: function(res) {
            console.log(res);
        }
        })
    },
    fail: function(res) {
        console.log('文件下载失败');
        wx.showToast({
            title: '文件下载失败',
            icon: 'none',
            duration: 2000
        })
    },
    complete: function(res) {},
})
},解决 2 下载预览多个文件
如果服务端传过来的文件有多个,可以采用如下方法,直接点击文件1,文件2,,,,,
2 wxml代码
直接将传过来的数据中的文件数组再进行列表渲染
<view wx:for="{{documentlist}}" wx:for-item="item" wx:key="id">
         <view class="content">
             <view class="title">时间</view>
                 <view value="{{item.date}}">{{item.date}}</view>
             </view>
    <view class="title">查看文件:</view>
        <view class="file" wx:for="{{item.filepath}}" bindtap="downloadFile"  wx:for-item="itemFile" wx:for-index="indx" 
        data-index='{{item.filePropagationPlanDetailID}}' data-url="{{itemFile}}">
        <view><text class="filepath">{{"文件"+(indx+1)}}</text></view>                             
                    </view>
    </view>2 js代码
downloadFile函数没有变化
- 本文作者: étoile
 
- 版权声明: 本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。转载请注明出处!