一、前言
在前端的项目开发中 ,下载文件压缩包是很重要的一个环节,那么怎么下载多个文件并压缩成ZIP下载呢?
二、使用步骤
1、引用库
<script type="text/javascript" src="~/Scripts/comm/jszip.min.js" ></script>
<script type="text/javascript" src="~/Scripts/comm/FileSaver.min.js" ></script>
库下载地址:https://download.csdn.net/download/u012949335/88088658
2、简单使用方法
var zip = new JSZip();
var zipName = "test";
var fileFolder = zip.folder(zipName);
fileFolder.file(fileList[k].name, fileList[k].content, {binary: true //二进制});
zip.generateAsync({type: 'blob'}).then(function(content){saveAs(content, zipName+'.zip');});
3、封装高级用法
/**
*批量下载文件
*@param { Array } array 待下载数据
*@param { String } data 参数,需包含属性gndm
*@param { String } dg datagrid的id
*@param { String } url 请求下载文件url
*@param { String } filefolder 压缩文件夹
*@param { String } zipname 下载文件名称
*@param { String } field 失败显示字段名称
*@param { Boolean } tooltips 是否显示提示信息
*@example $.ajaxRecursionZipDownFile({ array: infolist, data: { "gndm": gndm }, datagrid: "XX", url: 'XXXX', filefolder: "XX附件", zipname: "XX附件.zip", field: "xh" });
*/
jQuery.ajaxRecursionZipDownFile = function (option) {
if (typeof option === 'undefined') throw new Error("Please pass parameters");
if (typeof option.url === 'undefined') throw new Error("Please pass parameters url");
if (typeof option.array === 'undefined') throw new Error("Please pass parameters array");
if (typeof option.field === 'undefined' || option.field === null) option.field = "xh";
option.data = option.data || {};
if (option.data.hasOwnProperty('gndm') === false) throw new Error("Please pass parameters data->gndm");
option.zipname = option.zipname || "附件";
option.filefolder = option.filefolder || "附件";
option.tooltips = option.tooltips || false;
var zip = new JSZip();
var fileFolder = zip.folder(option.filefolder);
var fileName = '';
var _currentIndex = 0;
var _successIndex = 0;
var _faileXhInfo = '';
var _currentTotal = option.array.length;
pageLoadDown();
function _recursionZipDownFiles() {
if (_currentIndex >= _currentTotal) {
zip.generateAsync({ type: 'blob' }).then(function (content) {
saveAs(content, option.zipname);
dispageload();
var msg = "压缩成功:" + _successIndex.toString() + "个。失败数据:" + (_faileXhInfo || "无。");
if (option.datagrid) $('#' + option.datagrid).datagrid('clearChecked');
if (option.tooltips === true) {
$.messager.alert('提示', msg, 'infoxx');
if (!this._endmessagertimeout) {
window.clearTimeout(this._endmessagertimeout);
}
this._endmessagertimeout = setTimeout("$(\".messager-body\").window('close');", 1000);
}
});
return false;
}
var jsonObject = JSON.stringify(option.array[_currentIndex]);
var _objdata = option.data;
_objdata.json = jsonObject;
axios({
method: 'post',
url: option.url,
data: _objdata,
responseType: 'blob'
}).then(function (res) {
var data = res.data;
var reqHeader = res.headers;
if (reqHeader["content-disposition"]) fileName = decodeURI(reqHeader["content-disposition"]).split('; ')[1].split('filename=')[1];
if (data.size > 0) {
fileFolder.file(fileName, data, { binary: true });
_successIndex++;
} else {
_faileXhInfo += option.array[_currentIndex][option.field] + ";";
}
_currentIndex++;
_changeProcess(Math.round((_currentIndex / _currentTotal) * 100));
_recursionZipDownFiles(option.array, option.data.gndm);
}, function (err) {
_currentIndex++;
_faileXhInfo += option.array[_currentIndex][option.field] + ";";
_changeProcess(Math.round((_currentIndex / _currentTotal) * 100));
});
}
_recursionZipDownFiles();
}
4、调用示例
function getFilesZipDownInfo(gndm) {
var rows = $("#dg").datagrid('getChecked');
if (rows.length == 0) {
$.messager.alert('提示', "请选择要下载的数据!", "error");
return;
}
var infolist = [];
$.each(rows, function (index, row) {
var info = new Object();
info.idxx = row.idxx;
info.fjmcxx = row.fjmcxx;
infolist.push(info);
});
$.ajaxRecursionZipDownFile({
array: infolist,
data: { "gndm": gndm },
datagrid: "dg",
url: 'downfile',
filefolder: "实验报告附件",
zipname: "实验报告附件.zip",
field: "idxx",
tooltips: true
});
}
5、效果展示