前端js实现文件下载

export function downLoadFn(data, name) {
  const str = name.substring(name.lastIndexOf(".") + 1)// 截取获取图片类型
  let ContentType = ""
  switch (str) {        //在这里添加要下载文件的ContentType
    case "jpeg":
      ContentType = "image/jpeg"
      break
    case "jpg":
      ContentType = "image/jpeg"
      break
    case "gif":
      ContentType = "image/gif"
      break
    case "jfif":
      ContentType = "image/jpeg"
      break
    case "png":
      ContentType = "application/x-png"
      break
    case "doc":
      ContentType = "application/msword"
      break
    case "docx":
      ContentType =
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
      break
    case "pdf":
      ContentType = "application/octet-stream"
      break
    case "csv":
      ContentType = "text/csv,charset=UTF-8"
      break
    case "xlsx":
      ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      break
    default:
      ContentType = "image/jpeg"
      break
  }
  console.log(ContentType)
  const blog = new Blob([data], {
    type: ContentType
  })
  const url = window.URL.createObjectURL(blog)
  const a = document.createElement("a")
  a.download = `${name}` // 拼接得到图片名称
  a.href = url
  a.click()
  a.remove()
}

调用的话直接
downLoadFn(data,name)

// data为将要下载的文件数据 是Blob格式的

// name为文件名称要有文件类型后缀例如 “测试.word”

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值