前端實現(xiàn)下載文件(包含壓縮包下載)方式詳細總結(jié)
更新時間:2023年09月10日 14:55:53 作者:qq_38969618
這篇文章主要給大家介紹了關于前端實現(xiàn)下載文件(包含壓縮包下載)方式的相關資料,這段時間項目需要下載文件,所以這里給大家總結(jié)下,需要的朋友可以參考下
前言
默認最簡單的下載方式是:window.open(后臺接口API路徑),但該方法弊端:因是新開窗口方式,前端展示上,每次會閃下。
此外,如果使用window.open(文件URL)方式:
- pdf、office文檔、psd:直接下載。
- 圖片、txt:新開窗口預覽,不會下載;且txt預覽,有時出現(xiàn)中文亂碼問題。
一、根據(jù)文件URL下載
實現(xiàn)原理:通過a標簽實現(xiàn)下載。
/** * @method 下載單個文件(文件類型可任意:.png、txt、office文檔、.psd等) * @param { String } url - 文件的http完整路徑, 如:http: //xxx.png * @param { String } fileName - 文件名,注意是要帶文件后綴名,如:xxx.png * @doc https://blog.csdn.net/weixin_39547158/article/details/110851570 */ export function downloadFile(url: string, fileName: string) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'blob'; xhr.upload.onprogress = (e) => { if (e.lengthComputable) { let progress = e.loaded / e.total; console.log('文件上傳進度是', progress); } }; xhr.onload = function () { const url = window.URL.createObjectURL(xhr.response); const eleLink = document.createElement('a'); eleLink.href = url; eleLink.download = `${fileName}`; eleLink.style.display = 'none'; document.body.appendChild(eleLink); eleLink.click(); document.body.removeChild(eleLink); resolve('success'); }; xhr.onerror = (e) => { console.log('請求錯誤回調(diào)', e); message.warning('下載文件失敗') reject(e); }; xhr.send(); }); }
二、excel文件:調(diào)用后臺接口返回文件流,前端下載文件
實現(xiàn)原理:調(diào)用后臺接口,返回blob, 前端使用file-saver庫實現(xiàn)下載。
// 下載excel文件 import { saveAs } from 'file-saver'; const downloadTemplate = async () => { try { const params = { ... } // 傳參 const res = await generateDownStreamReconciliationUsingGET(params); // res為返回結(jié)果 if (res) { const blob = new Blob([res], { type: 'application/vnd.ms-excel' }); FileSaver.saveAs(blob, '對賬單.xlsx'); console.log('對賬單下載成功') } } catch (e) { console.log(e); } finally { console.log('finally') } };
// 生成對賬excel模板表格API export async function generateDownStreamReconciliationUsingGET( params: API.generateDownStreamReconciliationUsingGETParams, options?: { [key: string]: any }, ) { return request<any>( `${process.env.APP_HOST_WAYBILL}/xxx/generateDownStreamReconciliation`, { method: 'GET', responseType: 'blob', // 必須寫該行,否則:后臺返回的是string,不是blob且文件下載后,會出現(xiàn)打不開問題。 params: { ...params, }, ...(options || {}), }, ); }
三、多文件URL下載,前端生成壓縮包下載
實現(xiàn)原理:jszip庫 + file-saver庫
import { getBlobOfUrl } from '@/services/common'; import { saveAs } from 'file-saver'; import JSZip from 'jszip'; import { message } from 'antd'; /** * @method 同時下載多文件,并生成一個壓縮包 * @param { Object[] } fileInfoList - 文件列表 * @param { String } urlField - 文件URL的字段名 * @param { String } fileNameField - 文件名的字段名 * @param { String } folderName - 壓縮包 & 文件夾名稱 */ export function downloadAsZip( fileInfoList: any[], folderName = '文件壓縮包', urlField = 'filePath', fileNameField = 'name', ) { return new Promise((resolve, reject) => { const zip = new JSZip(); // const folder = zip.folder(folderName); // 創(chuàng)建文件夾 const promisesList = fileInfoList.map((item) => { return getBlobOfUrl(item[urlField]) .then((data) => { // console.log(data); // Blob // folder.file(item[fileNameField], data, { binary: true }); // 往文件夾中存放文件 zip.file(item[fileNameField], data, { binary: true }); // 不創(chuàng)建文件夾 }) .catch((e) => { console.log(e); message.warning(e?.message || '獲取文件流失敗') }); }); Promise.all(promisesList) .then(() => { zip .generateAsync({ type: 'blob' }) .then((content) => { saveAs(content, folderName); resolve('success'); }) .catch((e) => { message.warning(e?.message || '生成壓縮包失敗') reject(e); }); }) .catch((e) => { message.warning(e?.message || '批量獲取文件流失敗') reject(e); }); }); }
import { request } from 'umi'; /** * @method 根據(jù)文件URL獲取blob數(shù)據(jù)流的API * @param { String } fileUrl - 文件完整路徑,如:http://xxx.png */ export function getBlobOfUrl(fileUrl: string) { return request(fileUrl, { method: 'GET', responseType: 'blob', // 設置后臺返回的內(nèi)容類型為blob params: { notAuthorization: true, }, }); }
總結(jié)
到此這篇關于前端實現(xiàn)下載文件(包含壓縮包下載)方式的文章就介紹到這了,更多相關前端實現(xiàn)下載文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
JS常用插件之Swiper插件實現(xiàn)輪播圖功能實例
項目中會多次使用到輪播圖組件,下面這篇文章主要給大家介紹了關于JS常用插件之Swiper插件實現(xiàn)輪播圖功能的相關資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2024-07-07