vue开发app端使用H5+下载文件流

最近公司要求使用vue开发移动端跟app端,踩了好多坑!很不明白为什么不用uniapp,好气!
下面说说坑我最久的一个需求就是下载文件,知道怎么做了其他也不难

app端下载文件

先附上官方文档:https://www.html5plus.org/doc/zh_cn/downloader.html

而我们要使用的就是H5+中的plus.downloader模块管理网络文件下载任务
从使用方式我分为三部分,即直接访问资源地址、通过后端接口请求(分为get、post)

新建下载任务API

plus.downloader.createDownload(url, options, completedCB);

options参数的配置
在这里插入图片描述

具体详情看官方文档,下面我们直接讲开发中如何使用

一.访问资源地址

简单粗暴,直接贴代码

//资源地址
let picurl = `http://baidu.com/aa.png` 
// 参数
let data = {
    
    
	//自定义下载文件路径
    filename: "file://storage/emulated/0/yingjitong/aa.png",
    //默认为GET请求。注意这里需大写“GET”、“POST”
    method: 'GET', 
}
let dtask = plus.downloader.createDownload( picurl, data, (d, status)=>{
    
    
        // 下载完成
        if (status == 200) {
    
    
        	this.$toast( '导出成功' );
        	// 将本地URL路径转换成平台绝对路径
            plus.io.convertLocalFileSystemURL(d.filename);
        } else {
    
    
            dtask.clear(); //清除下载任务
            this.$toast( '导出失败' );
        }
    }
);
// 开始下载
dtask.start();

二.通过接口请求

get请求

//后端接口
let picurl = `http://xxx/api/downloadFile`
//get请求的参数需要拼接在接口后端,`http://xxx/api/downloadFile?name='123'`
// 参数
let data = {
    
    
	//自定义下载文件路径
    filename: "file://storage/emulated/0/yingjitong/aa.png",
    //默认为GET请求。注意这里需大写“GET”、“POST”
    method: 'GET', 
}
let dtask = plus.downloader.createDownload( picurl, data, (d, status)=>{
    
    
        // 下载完成
        if (status == 200) {
    
    
        	this.$toast( '导出成功' );
        	// 将本地URL路径转换成平台绝对路径
            plus.io.convertLocalFileSystemURL(d.filename);
        } else {
    
    
            dtask.clear(); //清除下载任务
            this.$toast( '导出失败' );
        }
    }
);
// 开始下载
dtask.start();

post请求,跟get请求的传参方式不同,需要添加请求头

// 后端接口
let picurl = `${
      
      httpUrl}/event/api/sjjbjbsj/exportSjjbjbsj`
let data = {
    
    
	// 参数
    data:params,
    filename: "file://storage/emulated/0/yingjitong/突发事件统计表.xls",
    //post必须大写
    method: 'POST',
}
let dtask = plus.downloader.createDownload( picurl, data, (d, status)=>{
    
    
    this.exportActive = true
        // 下载完成
        if (status == 200) {
    
    
            this.$toast( '导出成功' );
        	// 将本地URL路径转换成平台绝对路径
            plus.io.convertLocalFileSystemURL(d.filename);
        } else {
    
    
            dtask.clear(); //清除下载任务
            this.$toast( '导出失败' );
        }
    }
);
// post请求需要添加请求头
dtask.setRequestHeader( "Content-Type", "application/json" );
// 开始下载
dtask.start();

plus.downloader.createDownload中参数还有其他配置,有需要的可以看官方文档

猜你喜欢

转载自blog.csdn.net/qingshui_zhuo/article/details/122112780
今日推荐