下载post
export const download = (data, projectid) => { return request({ url: baseurl + '/xxx/xxx/xxx', headers: { "project-id": projectid, httpwhite: true, }, responsetype: "blob",//文件流 method: 'post', data }) }
<el-button size="small" type="primary" class="downloadtemplate" @click="downloadfile(row)"> <i class="iconfont yun-xiazai"></i> <span class="first">下载数据模板</span> </el-button> //点击下载 const downloadfile(row){ const params = { 需要传递的参数:'xxxx', id:row.id, //示例, } download(params, this.projectids).then((res) => { if (res.status === 200) { this.downloaddatatemplate(res); } }); } //下载数据模板 downloaddatatemplate(res) { if (!res.data) { return; } const filename = decodeuricomponent( res.headers["content-disposition"].split("filename=")[1] ); const blob = new blob([res.data], { type: "application/vnd.openxmlformats- officedocument.spreadsheetml.sheet;charset=utf-8", }); const downloadelement = document.createelement("a"); const href = window.url.createobjecturl(blob); // 创建下载的链接 downloadelement.href = href; // 文件名中有中文 则对文件名进行转码 downloadelement.download = filename; // 下载后文件名 document.body.appendchild(downloadelement); downloadelement.click(); // 点击下载 document.body.removechild(downloadelement); // 下载完成移除元素 window.url.revokeobjecturl(href); // 释放blob对象 },
get下载方法
通用get下载方法 99%可以使用
const downerror = `baseurl+/xxx/xxx/xxxx?${this.tokenheader}=${gettoken()}&projectid=${this.projectid}&spaceid=${this.spaceid}`; window.open(downerror, "_self");//调用window方法
特殊get下载方法 1%才能用到 一般用不到 (仅用于个人记录)
这种使用于需要在hearder里面添加projecrt-id等参数 一般的都不需要 主要看后端接口能不能使用
使用下面这种方法 最主要get下载的请求 是responsetype:blob 文件流
export const exportpersonnel = (params) => request({ url: baseurl + '/exportxxx/xxxx', headers: { "project-id": params.projectid, }, method: 'get', responsetype: 'blob', //文件流方法 params, })
// 导出 exportcustomer() { let downstr = { ...this.params }; exportpersonnel(downstr).then((r) => { if (r.status === 200) { //获取下载文件名 const filename = decodeuricomponent( r.headers["content-disposition"].split("filename=")[1] ); // 创建 a 元素 const link = document.createelement('a'); const href = window.url.createobjecturl(r.data)//创建下载链接 link.href = href;// 设置下载链接的 url link.style.display = "none"; link.download = filename; // 下载后文件名 document.body.appendchild(link); link.click(); // 点击下载 document.body.removechild(link); // 下载完成移除元素 window.url.revokeobjecturl(href); // 释放blob对象 } }); },
总结
到此这篇关于前端get/post请求下载文件多种方式的文章就介绍到这了,更多相关前端get/post请求下载文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论