前端下载文件数据流格式及url格式

数据流格式

if (response && response.config && response.config.responseType == 'blob') { 
  // 开始处理文件下载 - res.data为文件流
  let blobUrl = window.URL.createObjectURL(new Blob([response.data], {
    // 后台传递的文件类型 - 此处我是直接写死的
    // 也可以从后台获取的
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
 }));
 const link = document.createElement('a');
 link.style.display = 'none';
 link.href = blobUrl;
 const dis = response.headers['content-disposition']
 const filenameKey = 'filename='
 const indexOf = dis.indexOf(filenameKey)
 const filename = indexOf ? decodeURI(dis.substring(indexOf + filenameKey.length)) : '未知文件名'
 // fileName 文件的名称
 link.setAttribute('download', filename)
 document.body.appendChild(link)
 link.click()
 document.body.removeChild(link)
}

下载url格式

let link = document.createElement('a')
link.href = this.fileUrl (需要下载的文件url)
link.click()

相关:常见文件类型格式

常见文件类型格式:
// .xls: application/vnd.ms-excel
// .xlsx: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
// .txt: text/plain
//: .png/.jpg/etc:image/*
//.htm,.html: text/html
//.avi, .mpg, .mpeg, .mp4: video/*
//.mp3, .wav, etc: audio/*
//PDF: .pdf

相关:获取response header数据

在下载文件时,大多需要根据后端返回动态获取文件格式或者文件名等

let req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
let headers = req.getAllResponseHeaders().toLowerCase();
console.log(headers);
// 由于返回的是用\r\n来进行分割的字符串,需要做转换
let arr = headers.trim().split(/[\r\n]+/);
let headerMap = {};
arr.forEach(function (line) {
    let parts = line.split(': ')
    let header = parts.shift()
    let value = parts.join(': ')
    headerMap[header] = value
})
let contentType = headerMap['content-type'];
console.log('contentType: ', content-type);
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hyduan200

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值