代码块:
package com.zjht.manage.controller;
import com.alibaba.fastjson.JSONObject;
import com.zjht.manage.model.po.MCulturalRelic;
import com.zjht.manage.model.po.MData;
import com.zjht.manage.model.vo.MsgEnum;
import com.zjht.manage.model.vo.ResultInfo;
import com.zjht.manage.service.MCulturalRelicService;
import com.zjht.manage.service.MDataService;
import com.zjht.manage.util.CommonUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* 批量下载
*/
@RestController
@RequestMapping("/zipDownload")
public class zipDownloadController {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private MDataService mDataService;
@RequestMapping("/filedownload")
public void test(HttpServletResponse response, String fileid,HttpServletRequest request) throws IOException {
long start = System.currentTimeMillis();
String[] split = fileid.split(",");
List<String> fileids = Arrays.asList(split);
List<MData> files = mDataService.listAllFiles(fileids);
//判断是否为excel类型文件
if(CollectionUtils.isEmpty(files)) {
logger.error("查询无关联图片或者视频");
} else {
// 设置文件名
formatFileName(response,request);
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(response.getOutputStream());
for (MData srcFile : files) {
//String dataTitle=getCRC32Value(srcFile.getDataTitle());
String dataTitle=srcFile.getDataTitle()+"_"+System.currentTimeMillis();
if (StringUtils.isNotEmpty(srcFile.getUrl()) && StringUtils.isNotEmpty(dataTitle)) {
// 下载附件
byte[] bytes = getBytes(srcFile.getUrl());
byte[] buf = new byte[1024];
zos.putNextEntry(new ZipEntry(dataTitle));
int len;
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
while ((len = in.read(buf)) != -1){
zos.write(buf, 0, len);
}
zos.closeEntry();
}
}
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) +" ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils",e);
}finally{
if(zos != null){
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
/**
*
* @Title: getCRC32Value
* @author:liuyx
* @date:2015年11月6日下午5:26:12
* @Description: 获取字符串对应的重复概率较小的整形
* @param str 传入字符串
* @return
*/
public static String getCRC32Value(String str) {
CRC32 crc32 = new CRC32();
crc32.update(str.getBytes());
System.out.println(crc32.getValue());
return Long.toString(crc32.getValue());
}
/**
* @methodname formatFileName
* @Description {设置响应信息和格式化附件名字}
* @author admin
*/
private void formatFileName(HttpServletResponse response, HttpServletRequest request) throws UnsupportedEncodingException {
String fileName = "文物资料";
Long actualEndTime = new Date().getTime();
fileName += actualEndTime + ".zip";
// 获取浏览器信息
if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
fileName = new String(fileName.getBytes("GB2312"),"ISO-8859-1");
} else {
// 处理中文文件名的问题
fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
fileName = new String(fileName.getBytes("UTF-8"), "GBK");
}
// 清除首部的空白行
response.reset();
// 设置Response容器的编码
response.setCharacterEncoding("UTF-8");
// 不同类型的文件对应不同的MIME类型
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition","attachment; filename="+fileName);
}
private byte[] getBytes(String filePath){
byte[] buffer = null;
try {
HttpURLConnection connection = null;
InputStream inputStream = null;
RandomAccessFile randomAccessFile = null;
// 1.获取连接对象
URL url = new URL(filePath);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Range", "bytes=0-");
connection.connect();
if(connection.getResponseCode() / 100 != 2) {
System.out.println("连接失败...");
//return ResultInfo.error(MsgEnum.FAIL.getCode(), "连接失败...");
}
// 2.获取连接对象的流
inputStream = connection.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = inputStream.read(b)) != -1) {
bos.write(b, 0, n);
}
inputStream.close();
bos.close();
buffer = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}
}