适用于正常url链接,如有不对,请提出意见。谢谢各位大哥!!!(都是总结网上各位大哥的)
1.根据url 获取文件名称
let url='http://qqUniApp.oss-cn-hangzhou.aliyuncs.com/no/bank.png',filename;
if (url.indexOf('/') > 0) {
if (url.indexOf('?') > 0) {
url = url.split('?')[0];
}
//如果包含有"/"号 从最后一个"/"号+1的位置开始截取字符串
filename = url.substring(
url.lastIndexOf('/') + 1,
url.length
);
}
console.log(filename) //bank.png
已知文件名称获取文件类型
type= filename.split('.').slice(-999, -1).join('.')
console.log(type) //png
2. 根据url 获取文件类型
type=url.replace(/.+\./g,'')
console.log(type) //png
3. http 替换为https
url=url.replace(/^http:\/\//i,'https://')
4 根据url下载(我的在vue项目中用,没兼容所有浏览器)
export const downloadFile = (url, filename) => {
url = url.replace(/^http:\/\//i, 'https://');
axios
.get(url, {
responseType: 'blob',
})
.then((res) => {
const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' }) // 构造一个blob对象来处理数据,并设置文件类型
if (window.navigator.msSaveOrOpenBlob) {
// 兼容IE10
navigator.msSaveBlob(blob, filename)
} else {
const href = URL.createObjectURL(blob) // 创建新的URL表示指定的blob对象
const a = document.createElement('a')
a.style.display = 'none'
a.href = href // 指定下载链接
a.download = filename // 指定下载文件名
a.click()
URL.revokeObjectURL(a.href) // 释放URL对象
}
})
}