本文主要是介绍比钢筋还硬的硬货-单文件、多文件、excel文件下载,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
- 继上传图片、上传文件和处理文件格式之后,再继续又硬又干的干货单文件、多文件批量、excel下载完整版
注意:项目运用的是vue3框架,需要依赖axios、JSzip、FileSaver三个依赖包。缺一不可撒
- 安装三个依赖
npm install axios
npm install JSzip --save
npm install file-saver --save
-
创建FileHandle.js
-
FileHandle.js具体代码
import { fetchFileUpload } from '@/services/common.js'
import JSZip from 'jszip'
import FileSaver from 'file-saver'
import axios from 'axios'
import { ItMessage } from '@/components'/*** 文件处理*/// 归类的文件类型
const fileTypes = ['word','excel','ppt','pdf','image','gif','video','zip',
]// 支持的文件格式 每组二维数组元素对应一种文件类型,例如:['doc', 'docx'] 对应 'word'
const fileFormatCollections = [['doc', 'docx'],['xls', 'xlsx'],['ppt', 'pptx'],['pdf'],['jpg', 'jpeg', 'png', 'bmp'],['gif'],['mp4'],['zip', 'rar', '7z'],
]
const fileFormatMap = {projectVerify: ['doc','docx','xls','xlsx','ppt','pptx','pdf','jpg','jpeg','gif','png','bmp','mp4',],
}export function FileHandle() {// 校验文件格式const getAcceptFileFormats = (key) =>fileFormatMap[key].map((format) => `.${format}`).join(',')// 文件下载const downloadFile = async (url, name) => {if (!name) {let { fileName } = parseFileUrl(url)name = fileName}FileSaver.saveAs(url, name)}// 批量压缩下载/**** @param {Array} fileTable 文件路径数组* @param {String} fileTableTitle 文件zip名称*/function getFile(url) {return new Promise((resolve, reject) => {axios({method: 'get',url,responseType: 'blob',}).then((data) => {resolve(data.data)}).catch((error) => {reject(error.toString())})})}function handleBatchDownload(fileTable, filename) {const dataUrl = []for (let file of fileTable) {dataUrl.push(file.url) // 把所有要打包文件的url放进数组}const zip = new JSZip() // 创建一个JSZip实例const cache = {}const promises = []dataUrl.forEach((item) => {const promise = getFile(item).then((data) => {const arr_name = item.split('/') // stringObject.split 将字符串分割成字符串数组const file_name = arr_name[arr_name.length - 1] // 获取文件名(数组最后一项)zip.file(file_name, data, { binary: true }) // 逐个添加文件cache[file_name] = data})promises.push(promise)})Promise.all(promises).then(() => {zip.generateAsync({ type: 'blob' }).then((content) => {downloadFile(content, filename + '.zip')})})}// 判断上传文件类型是否在范围const applyArr = (arr, file) => {return new Promise((resolve, reject) => {//二维数组转一维数组let newArr = [].concat.apply([], arr)//文件类型let fileType = file.name.split('.')[file.name.split('.').length - 1]if (newArr.indexOf(fileType) == -1) {ItMessage({ content: '不支持该类型文件上传' })reject(false)} else {resolve(true)}})}// 文件上传const handleUploadFile = async (file) => {await applyArr(fileFormatCollections, file)if (file.name.indexOf(',') != -1) {ItMessage({ content: '文件名中不能有","' })return false} else {let res = await fetchFileUpload(file)const { fileName, fileType } = parseFileUrl(res.data)const fileObj = {timeid: new Date().getTime(),name: fileName,path: res.data,type: fileType,}return fileObj}}// 图片上传const fetchPicUpload = async (file) => {if (file.name.indexOf(',') != -1) {ItMessage({ content: '图片名中不能有逗号' })return false} else {let res = await fetchFileUpload(file)const { fileName, fileType } = parseFileUrl(res.data)const fileObj = {timeid: new Date().getTime(),name: fileName,path: res.data,type: fileType,}return fileObj}}// 根据链接返回文件名称、类型// in: https:/***/xxx.pdf// out: { fileName, fileFormat, fileType }const parseFileUrl = (fileUrl) => {let fileName = fileUrlif (fileUrl.includes('/')) {const splitedFile = fileUrl.split('/')const splitedFileLength = splitedFile.lengthfileName = splitedFile[splitedFileLength - 1]}const splitedFileName = fileName.split('.')const fileFormat = splitedFileName[splitedFileName.length - 1]const getFileType = (fileFormat) => {const filtedFileIndex = fileFormatCollections.map((fileFormats, index) => {if (fileFormats.includes(fileFormat)) {return index}}).filter((item) => item >= 0)[0]return fileTypes[filtedFileIndex]}const fileType = getFileType(fileFormat)return { fileName, fileFormat, fileType }}// htmlExportExcelconst htmlExportExcel = ({ html, name }) => {const stylecss = `table{border: none;}table td {font-size: 12px;height: 30px;text-align: center;color: #000;}.textLeft {text-align: left;}table td.tishi{text-align: left;font-size: 10px;border: none;height: 20px;}.tablehead{font-size: 20px;}`const base64 = (s) => {return window.btoa(unescape(encodeURIComponent(s)))}const uri = 'data:application/vnd.ms-excel;base64,'let template = `<html xmlns:o="urn:schemas-microsoft-com:office:office"xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><style type="text/css"> ${stylecss}</style></head><body><table class="excelTable" cellspacing="0" cellpadding="0" border="1" >${html}</table><body></html>`downloadFile(uri + base64(template), `${name || '数据'}.xls`)}// jsonToDocreturn {getAcceptFileFormats,parseFileUrl, // 根据链接返回文件名称、类型htmlExportExcel, // 导出为excelhandleUploadFile, // 上传文件handleBatchDownload, // 批量压缩下载downloadFile, // 文件下载fetchPicUpload, //上传图片}
}
FileHandle.js中fetchFileUpload
这篇关于比钢筋还硬的硬货-单文件、多文件、excel文件下载的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!