一、工具类 - package com.juanpi.service.util;
-
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.OutputStream;
- import java.util.zip.ZipEntry;
- import java.util.zip.ZipOutputStream;
-
- import javax.servlet.http.HttpServletResponse;
-
- public class CustomFileUtil {
-
-
-
-
-
-
-
-
- public static void zip(String inputFileName, String zipFileName) throws Exception {
- zip(zipFileName, new File(inputFileName));
- }
-
- private static void zip(String zipFileName, File inputFile) throws Exception {
- ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
- zip(out, inputFile, "");
- out.close();
- }
-
- private static void zip(ZipOutputStream out, File f, String base) throws Exception {
- if (f.isDirectory()) {
- File[] fl = f.listFiles();
- out.putNextEntry(new ZipEntry(base + "/"));
- base = base.length() == 0 ? "" : base + "/";
- for (int i = 0; i < fl.length; i++) {
- zip(out, fl[i], base + fl[i].getName());
- }
- } else {
- out.putNextEntry(new ZipEntry(base));
- FileInputStream in = new FileInputStream(f);
- int b;
- while ((b = in.read()) != -1) {
- out.write(b);
- }
- in.close();
- }
- }
-
-
-
-
-
-
-
- public static 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.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();
- }
- }
-
- }
二、restful接口 -
-
-
-
-
- @RequestMapping(value = "/loadFiles", method = RequestMethod.GET)
- public void downloadFiles(HttpServletRequest request, HttpServletResponse response,String param)
- throws ServletException, IOException {
-
- String inputFileName = "C:/test/";
- if (domain != null && !domain.trim().equals("")) {
- inputFileName = realPath + domain.toUpperCase();
- }
- logger.info("download file directory is :" + inputFileName);
- String zipFileName = realPath + "temp.zip";
- try {
- CustomFileUtil.zip(inputFileName, zipFileName);
- } catch (Exception ex) {
- logger.error(ex.getMessage());
- }
- File temp = new File(zipFileName);
- CustomFileUtil.downloadFile(temp, response, true);
- }
|