多个文件打包下载 java

来源:互联网 发布:关闭电脑软件自动更新 编辑:程序博客网 时间:2024/06/10 04:55
/**
* 批量打包下载文件生成zip文件下载
* @param request
* @param response
* @param downurl
* @return
* @throws Exception
*/
@RequestMapping("/downloadFiles")
   public void downloadFiles(HttpServletRequest request,HttpServletResponse response,String courseId,String  downurl,Integer courseType) throws Exception{
  List<File> files = new ArrayList<File>();
  String[] filePath = downurl.split("@");
   for(String file : filePath)

   {

            //获取文件完整的路径

    file=request.getSession().getServletContext().getRealPath("/").replaceFirst(GlobalConstants.PROJECT_NAME, GlobalConstants.PROJECT_FILE_NAME)+file;
    files.add(new File(file));
   }
   String fileName = "课程资源.zip";
   fileName=java.net.URLEncoder.encode(fileName, "UTF-8");//防止ie下文件名乱码
   //在服务器端创建打包下载的临时文件
   String outFilePath=request.getSession().getServletContext().getRealPath("/").replaceFirst(GlobalConstants.PROJECT_NAME, GlobalConstants.PROJECT_FILE_NAME);
   outFilePath +=  "文件夹名/"+fileName;
   File file = new File(outFilePath);
// 文件是否存在
if(!file.exists()){
file.createNewFile();
}
   //文件输出流
   FileOutputStream outStream = new FileOutputStream(file);
   //压缩流
   ZipOutputStream toClient = new ZipOutputStream(outStream);
   toClient.setEncoding("utf-8");
   zipFile(files, toClient);
   toClient.close();
   outStream.close();
   this.downloadFile(file, response,true);
}
   
/**
* 压缩文件列表中的文件

* @param files
* @param outputStream
* @throws IOException
*/
public  void zipFile(List<File> files, ZipOutputStream outputStream) throws IOException, ServletException {
List<String>fileNames=new ArrayList<String>();
try {
int size = files.size();
// 压缩列表中的文件
for (int i = 0; i < size; i++) {
File file = (File) files.get(i);
outputStream.setEncoding("GBK"); //设置压缩文件内的字符编码,不然会变成乱码  
CourseResources courseResources=courseResourcesService.findCourseResourcesByDownUrl("%"+file.getName());
String fileName=courseResources.getResourceName()+"."+courseResources.getFormat();//替换下载文件的文件名
//判断压缩文件内文件名是否有重复
if(!fileNames.contains(fileName)){
fileNames.add(fileName);
}else{
fileName=courseResources.getResourceName()+PingXXUtil.getFixLenthString(6)+"."+courseResources.getFormat();
}
zipFile(file, outputStream,fileName);
}
} catch (IOException e) {
throw e;
}
}


/**
* 将文件写入到zip文件中

* @param inputFile
* @param outputstream
* @throws Exception
*/
public  void zipFile(File inputFile, ZipOutputStream outputstream,String fileName) throws IOException, ServletException {
try {
if (inputFile.exists()) {
if (inputFile.isFile()) {
FileInputStream inStream = new FileInputStream(inputFile);
BufferedInputStream bInStream = new BufferedInputStream(inStream);
ZipEntry entry = new ZipEntry(fileName);
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();
}
}
0 0