通用的下载方法
/** * @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) }
下载文件
/** * @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 } }
下载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`) }
下载图片类型
/** * @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 } }
获取文件大小方法
/** * @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]}` }
获取文件类型
/** * @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' }
版权属于:
liangzai
作品采用:
《
署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)
》许可协议授权
评论 (0)