從服務器對指定的文件進行壓縮並下載

需求:對服務器中指定文件夾中的pdf進行提取、壓縮、下載

壓縮和下載的工具類

import com.good.service.utils.DateUtils;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/***
 * 將服務器中文件內容壓縮響應到瀏覽器並下載
 */
public class DownloadUtils {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final int BUFFER_SIZE = 2 * 1024;

    // 字符編碼格式
    private static String charsetCode = "utf-8";


    /**
     * 下載接口
     * @param filePath 需要下載的文件的路徑
     * @param partPath 拼湊路徑
     * @param tList 下載的文件的名稱
     * @param response
     * @param request
     * @return
     * @throws IOException
     */
    public static String downLoad(String filePath, String partPath, List<String> tList, HttpServletResponse response, HttpServletRequest request) throws IOException {
        List<File> fileList = new ArrayList<>();
        for (String list : tList) {
            fileList.add(new File(filePath + partPath + "/" + list + ".pdf"));
        }
        String srcFile = filePath + "/download" + DateUtils.getDate("yyyyMMddHHmmss") + ".zip";
        FileOutputStream fos2 = new FileOutputStream(new File(srcFile));
        toZipList(fileList, fos2);
        DownloadUtils.downloadFile(srcFile, "download.zip", response, request);
        File delFile = new File(srcFile);
        FileUtils.forceDelete(delFile);
        return null;
    }


    /**
     * 文件的內容類型
     */
    private static String getFileContentType(String name) {
        String result = "";
        String fileType = name.toLowerCase();
        if (fileType.endsWith(".png")) {
            result = "image/png";
        } else if (fileType.endsWith(".gif")) {
            result = "image/gif";
        } else if (fileType.endsWith(".jpg") || fileType.endsWith(".jpeg")) {
            result = "image/jpeg";
        } else if (fileType.endsWith(".svg")) {
            result = "image/svg+xml";
        } else if (fileType.endsWith(".doc")) {
            result = "application/msword";
        } else if (fileType.endsWith(".xls")) {
            result = "application/x-excel";
        } else if (fileType.endsWith(".zip")) {
            result = "application/zip";
        } else if (fileType.endsWith(".pdf")) {
            result = "application/pdf";
        } else {
            result = "application/octet-stream";
        }
        return result;
    }

    /**
     * 下載文件
     *
     * @param path     文件的位置
     * @param fileName 自定義下載文件的名稱
     * @param resp     http響應
     * @param req      http請求
     */
    public static void downloadFile(String path, String fileName, HttpServletResponse resp, HttpServletRequest req) {

        try {
            File file = new File(path);
            /**
             * 中文亂碼解決
             */
            String type = req.getHeader("User-Agent").toLowerCase();
            if (type.indexOf("firefox") > 0 || type.indexOf("chrome") > 0) {
                /**
                 * 谷歌或火狐
                 */
                fileName = new String(fileName.getBytes(charsetCode), "iso8859-1");
            } else {
                /**
                 * IE
                 */
                fileName = URLEncoder.encode(fileName, charsetCode);
            }
            // 設置響應的頭部信息
            resp.setHeader("content-disposition", "attachment;filename=" + fileName);
            // 設置響應內容的類型
            resp.setContentType(getFileContentType(fileName) + "; charset=" + charsetCode);
            // 設置響應內容的長度
            resp.setContentLength((int) file.length());
            // 輸出
            outStream(new FileInputStream(file), resp.getOutputStream());
        } catch (Exception e) {
            System.out.println("執行downloadFile發生了異常:" + e.getMessage());
        }
    }

    /**
     * 基礎字節數組輸出
     */
    private static void outStream(InputStream is, OutputStream os) {
        try {
            byte[] buffer = new byte[10240];
            int length = -1;
            while ((length = is.read(buffer)) != -1) {
                os.write(buffer, 0, length);
                os.flush();
            }
        } catch (Exception e) {
            System.out.println("執行 outStream 發生了異常:" + e.getMessage());
        } finally {
            try {
                os.close();
            } catch (IOException e) {
            }
            try {
                is.close();
            } catch (IOException e) {
            }
        }
    }

    /**
     * @param srcFiles 需要壓縮的文件列表
     * @param out      壓縮文件輸出流
     * @throws RuntimeException 壓縮失敗會拋出運行時異常
     */
    public static void toZipList(List<File> srcFiles, OutputStream out) throws RuntimeException {
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(out);
            for (File srcFile : srcFiles) {
                byte[] buf = new byte[BUFFER_SIZE];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1) {
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                in.close();
            }
            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();
                }
            }
        }
    }

響應接口

@GetMapping(value = "download")
    public void download(Sbfhjsq sbfhjsq, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String partPath = "/hjshbxf";
        List<Sbfhjsq> list = getService().queryForDownload(sbfhjsq);
        if (list.size() > 10) {
            List<Sbfhjsq> newList = list.subList(0, 10);
            List<String> zipList = new ArrayList<>();
            for (Sbfhjsq asList : newList) {
                zipList.add(asList.getPdfId());
            }
            DownloadUtils.downLoad(filePath, partPath, zipList, response, request);
        } else {
            List<String> zipList = new ArrayList<>();
            for (Sbfhjsq asList : list) {
                zipList.add(asList.getPdfId());
            }
            DownloadUtils.downLoad(filePath, partPath, zipList, response, request);
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章