您的位置:首页 > 编程语言 > Java开发

springmvc批量文件打包成zip下载功能

2015-07-20 08:57 495 查看
1.页面上遍历checkbox

$("#checkAll").click(function(){

if(this.checked){

$(".thesisCheck").attr("checked", true);

}else{

$(".thesisCheck").attr("checked", false);

}

});

//批量下载

function plDownload(){

var valArr = new Array;

var c=0;

$('input[name="selectThesis"]:checked').each(function(i){

valArr[i] = $(this).val();

c++;

});

if(c==0){

alert("请选择需要下载的文件!");

return;

}else{

var vals = valArr.join(',');//转换为逗号隔开的字符串

if(c==1){

window.location.href = "../thesis/download.do?tcLwId="+vals;

}else{

window.location.href = "../thesis/downloadZip.do?tcLwIds="+vals;

}

}

}

//教师论文批量打包下载

/**

* 批量打包下载文件生成zip文件下载

* @param session

*/

@RequestMapping("downloadZip.do")

public String downloadFiles(String tcLwIds,HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

{

List<File> files = new ArrayList<File>();

System.out.println("需要批量下载的教师论文文件id:tcLwIds:"+tcLwIds);

if(""==tcLwIds||null==tcLwIds){

System.out.println("下载的文件不存在");

return "redirect:tclist.do";

}

String[] tcLwIdArray = tcLwIds.split(",");

for(String tcLwId : tcLwIdArray)

{

ThesisCompetitionBean tc = thesisCompetitionService.getTcById(tcLwId);

File file = new File(request.getSession().getServletContext().getRealPath("/")

+ "/thesisCompetition/uploadFile/" + tc.getThesisUrl());

files.add(file);

}

String fileName = UUID.randomUUID().toString() + ".zip";

//在服务器端创建打包下载的临时文件

String outFilePath = request.getSession().getServletContext().getRealPath("/")

+ "/thesisCompetition/uploadFile/";

createFile(outFilePath,fileName);

File file = new File(outFilePath+fileName);

//文件输出流

FileOutputStream outStream = new FileOutputStream(file);

//压缩流

ZipOutputStream toClient = new ZipOutputStream(outStream);

toClient.setEncoding("gbk");

zipFile(files, toClient);

toClient.close();

outStream.close();

this.downloadFile(file, response,true);

return null;

}

//创建文件

public void createFile(String path,String fileName){

//path表示你所创建文件的路径

File f = new File(path);

/*if(!f.exists()){

f.mkdirs();

} */

// fileName表示你创建的文件名;为txt类型;

File file = new File(f,fileName);

if(!file.exists()){

try {

file.createNewFile();

} catch (IOException e) {

e.printStackTrace();

}

}

}

/**

* 压缩文件列表中的文件

* @param files

* @param outputStream

* @throws IOException

*/

public static void zipFile(List<File> files, ZipOutputStream outputStream) throws IOException,ServletException

{

try {

int size = files.size();

// 压缩列表中的文件

for (int i = 0; i < size; i++) {

File file = (File) files.get(i);

zipFile(file, outputStream);

}

} catch (IOException e) {

throw e;

}

}

/**

* 将文件写入到zip文件中

*

* @param inputFile

* @param outputstream

* @throws Exception

*/

public static void zipFile(File inputFile, ZipOutputStream outputstream) throws IOException,ServletException

{

try {

if (inputFile.exists()) {

if (inputFile.isFile()) {

FileInputStream inStream = new FileInputStream(inputFile);

BufferedInputStream bInStream = new BufferedInputStream(

inStream);

ZipEntry entry = new ZipEntry(inputFile.getName());

outputstream.putNextEntry(entry);

final int MAX_BYTE = 10 * 1024 * 1024; // 最大的流为10M

long streamTotal = 0; // 接受流的容量

int streamNum = 0; // 流需要分开的数量

int leaveByte = 0; // 文件剩下的字符数

byte[] inOutbyte; // byte数组接受文件的数据

streamTotal = bInStream.available(); // 通过available方法取得流的最大字符数

streamNum = (int) Math.floor(streamTotal / MAX_BYTE); // 取得流文件需要分开的数量

leaveByte = (int) streamTotal % MAX_BYTE; // 分开文件之后,剩余的数量

if (streamNum > 0) {

for (int j = 0; j < streamNum; ++j) {

inOutbyte = new byte[MAX_BYTE];

// 读入流,保存在byte数组

bInStream.read(inOutbyte, 0, MAX_BYTE);

outputstream.write(inOutbyte, 0, MAX_BYTE); // 写出流

}

}

// 写出剩下的流数据

inOutbyte = new byte[leaveByte];

bInStream.read(inOutbyte, 0, leaveByte);

outputstream.write(inOutbyte);

outputstream.closeEntry(); // Closes the current ZIP entry

// and positions the stream for

// writing the next entry

bInStream.close(); // 关闭

inStream.close();

}

} else {

throw new ServletException("文件不存在!");

}

} catch (IOException e) {

throw e;

}

}

/**

* 下载文件

* @param file

* @param response

*/

public void downloadFile(File file,HttpServletResponse response,boolean isDelete) {

try {

// 以流的形式下载文件。

BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));

byte[] buffer = new byte[fis.available()];

fis.read(buffer);

fis.close();

// 清空response

response.reset();

OutputStream toClient = new BufferedOutputStream(response.getOutputStream());

response.setContentType("application/octet-stream");

response.setHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes("UTF-8"),"ISO-8859-1"));

toClient.write(buffer);

toClient.flush();

toClient.close();

if(isDelete)

{

file.delete(); //是否将生成的服务器端文件删除

}

}

catch (IOException ex) {

ex.printStackTrace();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: