springboot 프로젝트 에서 서버 파일 압축 zip 형식 다운로드 기능

29314 단어 SpringBoot
서버 에 저 장 된 업로드 파일 을 로 컬 에 대량으로 다운로드 합 니 다. 인터넷 자 료 를 참고 하여 서버 파일 을 zip 압축 파일 로 포장 한 다음 로 컬 에 다운로드 합 니 다. 코드 는 다음 과 같 습 니 다.
1. pom. xml 에 FileUtils 와 IOUtils 도구 류 의존 도 를 추가 합 니 다.

    commons-io
    commons-io
    2.2

2. 서버 쪽 에 임시 zip 형식 파일 만 들 기
3. 서버 의 모든 파일 을 새 임시 zip 압축 파일 에 입력
4. zip 파일 을 로 컬 에 다운로드
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
Sbcpolicylabel sbcpolicylabel = sbCommonService.findDowInfoByPolicy(policyNo);
ArrayList iconNameList = new ArrayList();//       

String zipName = UUID.randomUUID().toString()+".zip";
String outFilePath = request.getSession().getServletContext().getRealPath("/")+"upload";
File fileZip = new File(outFilePath+zipName);
if("filecomplaintflag".equals(flag)){
    try {
        if ((sbcpolicylabel.getFilecomplaint() != null || !"".equals(sbcpolicylabel.getFilecomplaint()) || !"null".equals(sbcpolicylabel.getFilecomplaint()))) {

            String filecomplaintpath = sbcpolicylabel.getFilecomplaint();
            List fileList = FileUtil.getFiles(filecomplaintpath);
            FileOutputStream outStream = new FileOutputStream(fileZip);
            ZipOutputStream toClient = new ZipOutputStream(outStream);
            IOtools.zipFile(fileList,toClient);
            toClient.close();
            outStream.close();
            IOtools.downloadFile(fileZip,response,true);
            return null;

        //      
        /**
            for (int i = 0; i < fileList.size(); i++) {
                String curpath = fileList.get(i).getPath();//      
                iconNameList.add(curpath.substring(curpath.lastIndexOf("\\") + 1));//        

                String fileName = new String(filecomplaintpath.getBytes("UTF-8"),"iso8859-1");
                headers.setContentDispositionFormData("attachment", fileName);
                return new ResponseEntity[]>(FileUtils.readFileToByteArray(new File(filecomplaintpath)),
                        headers, HttpStatus.OK);
            }
         **/
        }
    }catch(Exception e){
        log.info("    ,     !");
        e.printStackTrace();
    }

IOtools 도구 클래스
public class IOtools {

    /**
    *             
    */
    public static void zipFile(List 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;
        }
    }
    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;
        }
    }

    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
            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();
        }
    }

}

폴 더 아래 파일 과 디 렉 터 리 를 재 귀적 으로 옮 겨 다 니 는 방법
public static ArrayList getFiles(String path) throws Exception {
    //    fileList
    ArrayList fileList = new ArrayList();
    File file = new File(path);
    if(file.isDirectory()){
        File []files = file.listFiles();
        for(File fileIndex:files){
            //            if(fileIndex.isDirectory()){
                getFiles(fileIndex.getPath());
            }else {
             //                fileList.add(fileIndex);
            }
        }
    }
    return fileList;
}

좋은 웹페이지 즐겨찾기