js 关于根据url获取图片名称,图片类型,http替换https,以及根据url下载操作

适用于正常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对象
      }
    })
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值