您的位置:首页 > 大数据 > 人工智能

IntelliJ IDEA 工具grails实现多个文件压缩下载

2016-03-21 16:50 399 查看
1.在前台页面中使用checkbox多选复选框,对文件进行选择

2.前台数据传到后台,前台代码,前台选中多个文件,对文件的id进行一次性传输

$("#exportSelected").click(function(){
var checkbox = $("input[name='test']:checked");
//对checkbox进行判断是否进行选中,
if(checkbox.size() > 0){
var ids = ""
$(checkbox).each(function(){
ids +=  $(this).attr("id")+"|";//对选中的多个文件的id进行拼接
});

$("#ids").val(ids);
document.forms[0].action ="${createLink(controller: 'download', action: 'downloadMoreFile')}";
document.forms[0].submit();
} else {
window.alert("Please select at least one record to be exported!");
return;
}
});
});


3.后台语言

在工程文件中的Config.groovy配置文件中进行下载文件的基本路径进行配置

environments {
development {
grails.logging.jul.usebridge = true
manageengine.basePath = "D:\\test\\"//下载文件在本地D盘test文件夹中
}
}


4.DownloadControoler中编写downloadMoreFile方法

def downloadMoreFile() {
def basePath = grailsApplication.config.manageengine.basePath//获取配置文件中的文件存放地址
def fileId = null; def _attrs;
def ids = params.ids?.split("\\|")//获取前台传输的多个id,并进行拆分
String zipFileName = "${basePath}${fileName}.zip"//设置压缩文件名
List<File> files = new ArrayList<File>()
ids.each() {//遍历每个文件的id
String FileName = "${basePath}${it}.txt"//设置每个文件的文件名
File file = new File(mfFileName);
if (file.exists()) {//判断文件是否存在
files.add(file);//将每个文件放在文件集合中
}
}
commonService.zip(files, zipFileName)//对多个文件的集合体进行压缩
File zipFile = new File(zipFileName)
response.setContentType("application/zip")//设置请求体
response.setHeader("Content-disposition", "attachment;filename=${fileName}.zip")//设置请求头
response.outputStream << zipFile.newInputStream()//下载数据

}

/*******************commonService.zip方法(xx,xx)**************************/

public void zip(List<File> files, String zipFileName) {

OutputStream os = null;
BufferedOutputStream bos = null;
try {
os = new FileOutputStream(zipFileName);
bos = new BufferedOutputStream(os);
ZipOutputStream zos = new ZipOutputStream(bos);
for (File file : files) {
String basePath = null;
if (file.isDirectory()) {
basePath = file.getPath();
} else {
basePath = file.getParent();
}
zipFile(file, basePath, zos);
}
zos.closeEntry();
zos.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息