Dynamically generated Java files, directories and compression download

Dynamically generated files, directories
@GetMapping(value = "/downloadZip")
public void  downloadZips(HttpServletRequest request,HttpServletResponse response,Long taskId) throws IOException {
    List<taskFilesVO> vo=caseFilesService.getTaskFiles(taskId);
    String rootPath = request.getSession().getServletContext().getRealPath("/");
    File temDir = new File(rootPath + "/" + "定价文件");
    if(!temDir.exists()){
        temDir.mkdirs();
    }
    for (taskFilesVO taskvo:VO) {
        new new
        File Folder =dynamically generated directory// File(temDir + "/" +taskvo.getWorkStepName());
        if(!folder.exists()){
            folder.mkdirs();
        }
        if(taskvo.getWorkStepId()==0)
            createCoverExcel(folder+ "/封皮.xls",taskvo.getPrTaskDetail());
        else if(taskvo.getWorkStepId()==1)
            createLogExcel(folder+ "/目录.xls",vo);
        else{
            for (PrTaskFile file : taskvo.getPrTaskFileList()) {
                byte[] f=fileUploadService.downloadFile(file.getFileUrl());//将服务器文件下载到本地
                FileOutputStream fos = new FileOutputStream(folder+ "/" +file.getFileName());
                fos.write(f);
            }
        }
    }
    String zipFrontFile="定价文件.zip";
    zipFrontFile = URLEncoder.encode(zipFrontFile);
    response.setHeader("Content-Disposition","attachment; filename=" +zipFrontFile);
    response.setContentType("application/zip;");// 定义输出类型
    response.setStatus(200);
    ZipFilesUtil.toZip(temDir.getPath(), response.getOutputStream(),true);
    delFile(temDir);
}
//生成Excel
public void createCoverExcel(String filename, taskDetailVO prTaskDetail) {
    try {
        FileOutputStream out = new FileOutputStream(filename);
        HSSFWorkbook workBook = new HSSFWorkbook();
        HSSFSheet mySheet = workBook.createSheet();
        workBook.setSheetName(0, "cover");
        int rowNomber=-1;
        HSSFRow myRow = mySheet.createRow(++rowNomber);
        HSSFCellStyle style =workBook.createCellStyle ();
        style.setAlignment (CellStyle.ALIGN_CENTER); 
        style.setVerticalAlignment (CellStyle.VERTICAL_CENTER); 
        style.setWrapText (  );to true );
         // set the font style 
        HSSFFont font = workBook.createFont (); 
        font.setFontName ( "Song" ); 
        font. setFontHeightInPoints (( Short ) 10 ); 
        style.setFont (font); 
        // set the header row of each column heading 
        HSSFCell Cell myRow.createCell = (( Short ) 0 ); 
        cell.setCellStyle (style); 
        cell.setCellValue ( " government pricing dossier " 
        CellRangeAddress Region =new CellRangeAddress(0, 0, 0, 1);
        mySheet.addMergedRegion(region);

        for (int i = 1; i <= 5; i++) {
            HSSFRow row = mySheet.createRow(++rowNomber);
            HSSFCell cellfirst = row.createCell((short) 0);
            HSSFCell cellsecond = row.createCell((short) 1);
            if (i == 1) {
                cellfirst.setCellValue("定价项目");
                cellsecond.setCellValue(prTaskDetail.getName());
            }
            else if (i == 2) {
                cellfirst.setCellValue("定价单位");
                cellsecond.setCellValue(prTaskDetail.getUnitName());
            }
            else if (i == 3) {
                cellfirst.setCellValue("定价时间");
                if(prTaskDetail.getFinishTime()!=null)
                {
                    HSSFCellStyle dateCellStyle=workBook.createCellStyle();
                    short df=workBook.createDataFormat().getFormat("yyyy-mm-dd");
                    dateCellStyle.setDataFormat(df);
                    String temp= new SimpleDateFormat("yyyy-MM-dd").format(prTaskDetail.getFinishTime());
                    cellsecond.setCellValue(temp);
                }
            }
            else if (i == 4) {
                cellfirst.setCellValue("定价文件编号");
                cellsecond.setCellValue(prTaskDetail.getReferenceNumber());
            }
            else if (i == 5) {
                cellfirst.setCellValue("保存期限");
                cellsecond.setCellValue("20年");
            } 
        }
        workBook.write(out);
        out.close();
    } 
    The catch (Exception E) { 
        e.printStackTrace (); 
    } 
} 
// generate Excel 
public  void createLogExcel (String filename, List <taskFilesVO> filesList) {
     the try {
         // set the output to a local name and path excel file 
        FileOutputStream = OUT new new FileOutputStream (filename);
         // generate excel document object 
        HSSFWorkbook workBook = new new HSSFWorkbook ();
         // create a workbook 
        HSSFSheet MySheet = workBook.createSheet ();
         // set the name of the workbook
        workBook.setSheetName (0, "Catalog" ););
         // create the first row, the header row 
        int rowNomber = -1 ; 
        HSSFRow myRow = mySheet.createRow (++ rowNomber); 
        HSSFCellStyle style = workBook.createCellStyle ();
         // set the font style 
        HSSFFont font = workBook.createFont ( ); 
        font.setFontName ( "Song" ); 
        font.setFontHeightInPoints (( Short ) 10 ); 
        style.setFont (font); 
        // set the header row of each column heading 
        HSSFCell Cell myRow.createCell = (( Short ) 0 
        Cell .setCellStyle (style); 
        cell.setCellValue ("序号");
        cell = myRow.createCell((short) 1);
        cell.setCellStyle(style);
        cell.setCellValue("材料名称");

        cell = myRow.createCell((short) 2);
        cell.setCellStyle(style);
        cell.setCellValue("页码");
        cell = myRow.createCell((short) 3);
        cell.setCellStyle(style);
        cell.setCellValue("备注");
        for(int i = 1; i <= filesList.size(); i++){
            Row HSSFRow = mySheet.createRow (++ rowNomber); 
            taskFilesVO File = filesList.get (. 1-I );
             // create a column in a row, and assignment 
            HSSFCell cellfirst row.createCell = (( Short ) 0 ); 
            cellfirst.setCellValue (I); 
            HSSFCell cellsecond = row.createCell (( Short ). 1 ); 
            cellsecond.setCellValue (file.getWorkStepName ()); 
        } 
        // write the file to the local 
        workBook.write (OUT); 
        the out.close (); 
    } the catch  (Exception e) {
        e.printStackTrace (); 
    } 
}
//删除本地文件及目录
public boolean delFile(File file) {
    if (!file.exists()) {
        return false;
    }
    if (file.isDirectory()) {
        File[] files = file.listFiles();
        for (File f : files) {
            delFile(f);
        }
    }
    return file.delete();
}

//下载代码到本地
public byte[] downloadFile(String fileUrl) throws IOException {
String group = fileUrl.substring(0, fileUrl.indexOf("/"));
String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
DownloadByteArray downloadByteArray = new DownloadByteArray();
byte[] bytes = fastFileStorageClient.downloadFile(group, path, downloadByteArray);
return bytes;
}
 

 

Compression Tools
Package com.panchina.util; 


Import the java.io. * ;
 Import java.util.List;
 Import the java.util.zip *. ; 

public  class ZipFilesUtil {
     Private  static  Final  int BUFFER_SIZE 1024 = 2 * ; 

    / ** 
     * compressed into method ZIP. 1 
     * 
     * @param srcdir 
     * compressed folder path 
     * @param OUT 
     * compressed file output stream 
     * @param KeepDirStructure 
     * whether to retain the original directory structure, true: preserve the directory structure; 
     * to false: all files in the root directory went compressed (note: do not retain the directory structure of files of the same name may appear , compresses failure) 
     * @throws RuntimeException 
     * compression failure will throw an exception when running 
     * / 
    public  static  void toZip (String srcdir, the OutputStream OUT, Boolean KeepDirStructure) { 
        the ZipOutputStream ZOS = null ;
         the try { 
            ZOS = new new the ZipOutputStream (OUT); 
            File a sourceFile = new new File (srcdir); 
            the compress (a sourceFile, ZOS, sourceFile.getName (), KeepDirStructure); 
        } the catch (Exception e) {
            e.printStackTrace (); 
        } the finally {
             ZOSIF (ZOS =! null ) {
                 the try { 
                    zos.close (); // Finally, you must close ZipOutputStream, or it may be compressed data malformed packet error 

                } the catch (IOException E) { 
                    e.printStackTrace (); 
                } 
            } 
        } 
    } 
    / ** 
     * 
     * recursive compression method 
     * 
     * @param a sourceFile 
     * source file 
     * 
     * @param 
     * ZIP output stream 
     * 
     * @param name 
     * Name compressed 
     * 
     * @param KeepDirStructure 
     * whether to retain the original directory structure, true: preserving the directory structure; 
     * 
     * false: all the files went to the archive root directory (Note: not retained The directory structure might appear the same file, compresses failure) 
     * 
     * @throws Exception 
     * 
     * / 
    Private  static  void the compress (a sourceFile file, the ZipOutputStream ZOS, String name,
                                  Boolean KeepDirStructure) {
         byte [] = buf new new  byte [BUFFER_SIZE];
         the try{
             IF (sourceFile.isFile ()) {
                 // add a zip zip entity to the output stream, the constructor of the zip file name is the name of the entity 
                zos.putNextEntry ( new new the ZipEntry (name));
                 // Copy the file to the zip output stream 
                int len; 
                the FileInputStream in = new new the FileInputStream (a sourceFile);
                 the while (! (len = in.read (buf)) = -1 ) { 
                    zos.write (buf, 0 , len); 
                } 
                // Complete the entry 
                zos.closeEntry (); 
                in.close (); 
            } the else{ 
                File [] the listFiles =sourceFile.listFiles ();
                 IF (the listFiles == null || listFiles.length == 0 ) {
                     // when the need to keep the original file structure, the need for an empty folder for processing 
                    IF (KeepDirStructure) {
                         // empty folders processing 
                        zos.putNextEntry ( new new the ZipEntry (name + "/" ));
                         // no file, copy the file does not need 
                        zos.closeEntry (); 
                    } 
                } the else {
                     for (file file: the listFiles) {
                         // determines whether reserved the original file structure 
                        if (KeepDirStructure) {
                             // NOTE: file.getName () need to bring in front of the folder name of the parent plus a slash,
                             // otherwise finally compressed package can not retain the original file structure, namely: all documents have come to the root directory archive 
                            the compress (file, ZOS, name + "/" + file.getName (), KeepDirStructure); 
                        } the else { 
                            the compress (file, ZOS, file.getName ( ), KeepDirStructure); 
                        } 
                    } 
                } 
            } 
        } the catch (Exception E) { 
            e.printStackTrace (); 
        } 
    } 
}
Front-end interface to download vue call

downloadAll() {
axios({
method: "GET",
url: "/price/api/electronicFiles/downloadZip",
params: {
taskId: this.$route.query.id
},
responseType: "blob"
})
.then(response => {
let blob = new Blob([response.data], { type: "application/zip" });
let url = window.URL.createObjectURL(blob);
window.location.href = url;
})
.catch(error => this.$message.error(error));
}

 
 

Guess you like

Origin www.cnblogs.com/yyjspace/p/11890021.html