几种不同格式的下载方法和文件类型大小的方法
侧边栏壁纸
  • 累计撰写 15 篇文章
  • 累计收到 0 条评论

几种不同格式的下载方法和文件类型大小的方法

liangzai
2025-01-03 / 0 评论 / 1 阅读 / 正在检测是否收录...
  1. 通用的下载方法

    /**
     * @description 通用下载方法
     * @param {Blob} blob 文件blob
     * @param {String} filename 文件名
     */
    export const download = (blob, filename) => {
      const link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      link.download = filename
      link.click()
      window.URL.revokeObjectURL(link.href)
    }
  2. 下载文件

    /**
     * @description 下载文件
     * @param {String} url 文件地址
     * @param {String} filename 文件名
     */
    export const downloadFile = async (url, filename) => {
      try {
     const response = await fetch(url)
     const blob = await response.blob()
     download(blob, filename)
      } catch (error) {
     console.error('下载失败:', error)
     throw error
      }
    }
  3. 下载Excel文件

    #需要安装XLSX插件
    npm install xlsx
    yarn add xlsx
    pnpm add xlsx
    /**
     * @description 下载Excel文件
     * @param {Array} data 数据数组
     * @param {String} filename 文件名
     * @param {Array} headers 表头
     */
    export const downloadExcel = (data, filename, headers) => {
      // 创建工作簿
      const worksheet = XLSX.utils.json_to_sheet(data, { header: headers })
      const workbook = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')
      
      // 生成excel文件并下载
      const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })
      const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
      //第一个方法
      download(blob, `${filename}.xlsx`)
    }
  4. 下载图片类型

    /**
     * @description 下载图片
     * @param {String} url 图片地址
     * @param {String} filename 文件名
     */
    export const downloadImage = async (url, filename) => {
      try {
     const response = await fetch(url)
     const blob = await response.blob()
     const ext = url.split('.').pop().split('?')[0]
     //调用上面第一个方法
     download(blob, `${filename}.${ext}`)
      } catch (error) {
     console.error('图片下载失败:', error)
     throw error
      }
    }
  5. 获取文件大小方法

    /**
     * @description 获取文件大小
     * @param {Number} bytes 字节数
     * @param {Number} decimals 小数位数
     * @return {String}
     */
    export const formatBytes = (bytes, decimals = 2) => {
      if (bytes === 0) return '0 Bytes'
      
      const k = 1024
      const dm = decimals < 0 ? 0 : decimals
      const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
      
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      
      return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`
    }
  6. 获取文件类型

    /**
     * @description 获取文件类型
     * @param {String} filename 文件名
     * @return {String}
     */
    export const getFileType = (filename) => {
      const ext = filename.split('.').pop().toLowerCase()
      const typeMap = {
     // 图片
     'jpg': 'image',
     'jpeg': 'image',
     'png': 'image',
     'gif': 'image',
     'webp': 'image',
     // 文档
     'doc': 'document',
     'docx': 'document',
     'pdf': 'document',
     'txt': 'document',
     // 表格
     'xls': 'spreadsheet',
     'xlsx': 'spreadsheet',
     'csv': 'spreadsheet',
     // 压缩包
     'zip': 'archive',
     'rar': 'archive',
     '7z': 'archive',
     // 音视频
     'mp3': 'audio',
     'mp4': 'video',
     'avi': 'video'
      }
      return typeMap[ext] || 'unknown'
    }
0

评论 (0)

取消