前端实现下载文件或者下载视频

本文介绍了前端如何实现文件和视频的下载功能。通过提供一个兼容IE的文件下载方法,以及直接使用链接进行视频下载的方式,帮助开发者实现前端下载需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下载功能相比大家已经不陌生了吧

这都是基本常规操作啦!直接上代码

一. 文件下载

  1. 先写好下载的方法

export default function getDownloadData(content, name) {
  const blob = new Blob([content])
  if ('download' in document.createElement('a')) {
    // 非IE下载
    const elink = document.createElement('a')
    elink.download = name
    elink.style.display = 'none'
    elink.href = window.URL.createObjectURL(blob)
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href)  // 释放URL对象
    document.body.removeChild(elink)
  } else {
    
    // IE10+ 下载
    navigator.MsSaveBlob(blob, name)
  }

}

  2.在页面中使用

<div @click="clickDownloadFile(item)">下载</div>

import {downloadFile} from '@/api/api.js'  // 引入下载接口 
import download from '@/utils/download.js'  // 引入写好的下载方法


methods: {
  async clickDownloadFile(file) {
    let res = await downloadFile({
      fileName: file.name,
      url: file.url
    })
    if (res) {
      const content = res  // 接口返回文件流值
      download(content, file.name)
    }
  }
}

   3.api文件中的写法

import {axios} from '@/utils/request'

const api = {
  downloadFile: '/xxxx/xxxx/download.do'
}

export function downloadFile(data) {
  return axios({
    url: api.downloadFile,
    method: 'get',
    data,
    responseType: 'blob'
  })
}

这样就可以实现文件的下载啦!兼容IE的写法

二. 视频的下载

这个是直接使用的链接下载,无需调用接口

downloadVideo(url, name) {
  let link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  link.setAttribute('download', name)
  document.body.appendChild(link)
  link.click()
  return this.$message.success('下载成功')
}

 这就是我总结的两个下载的方法,欢迎大家提出更好的意见哦~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值