Java开发工具

压缩文件到zip返回

2019-05-28  本文已影响0人  墨色尘埃

管局项目 SystemController-getZip

GET方式:返回 IO流,接口调用成功后会直接下载

方法一:创建一个空zip文件夹,往文件夹里写入文件

                // 创建文件输出流
                FileOutputStream fous = new FileOutputStream(file);
                ZipOutputStream zipOut = new ZipOutputStream(fous);

方法二:不创建空zip文件,使用 HttpServletResponse的getOutputStream()直接返回

                OutputStream outputStream = response.getOutputStream();
                //这种方式是浏览器默认下载方式,返回的io流给前端
                ZipOutputStream zipOut = new ZipOutputStream(outputStream);

POST方式:返回 IO流,接口调用成功后会直接下载

方法一:创建一个空zip文件夹,往文件夹里写入文件

                // 创建文件输出流
                FileOutputStream fous = new FileOutputStream(file);
                ZipOutputStream zipOut = new ZipOutputStream(fous);

代码

GET方式

    @RequestMapping(value = "/zip", method = RequestMethod.GET)
    public void getZip(@RequestParam("fileIds") List<Long> fileIds, HttpServletResponse response) throws Exception {

        response.setContentType("application/octet-stream");
        response.setHeader("Cache-Control", "max-age=604800");
        // 如果输出的是中文名的文件,在此处就要用URLEncoder.encode方法进行处理
        String name = "生成zip文件" + "-" + IdWorker.getId() + ".zip";
        String fileName = new String(name.getBytes(), "ISO-8859-1");
        response.setHeader("Content-Disposition", String.format("attachment;filename=\"%s\"", fileName));

        List<FileModel> fileModelList = fileService.selectList(new EntityWrapper<FileModel>().in("FILE_ID", fileIds));
        //两种方法都可以
        fileService.downloadZipFile1(fileName, fileModelList, response.getOutputStream());
//        fileService.downloadZipFile(fileName, fileModelList, response.getOutputStream());

    }
    /**
     * 这种方式是浏览器默认下载方式,返回IO流,GET方式
     * @param fileName
     * @param fileModelList
     * @param outputStream
     * @return
     */
    public String downloadZipFile1(String fileName, List<FileModel> fileModelList, OutputStream outputStream) {

        if (fileModelList.size() > 0) {
            File file = null;

            try {

                Date now = new Date();
                java.text.DateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd");
                //按照时间来分文件夹
                String dateString = format.format(now);
                fileName = fileName + "-" + IdWorker.getId() + ".zip";

                file = fileOperation.createZip(dateString, fileName);

//                // 创建文件输出流
//                FileOutputStream fous = new FileOutputStream(file);
//                ZipOutputStream zipOut = new ZipOutputStream(fous);
                //这种方式是浏览器默认下载方式,返回的io流给前端
                ZipOutputStream zipOut = new ZipOutputStream(outputStream);

                for (FileModel fileModel : fileModelList) {
                    InputStream inputStream = fileOperation.downFile(fileModel.getFilePath().substring(7), fileModel
                            .getFileName());
                    FileUtils.zipFile(inputStream, zipOut, fileModel.fileOriginName + "." + fileModel.getFileType());
                    inputStream.close();
                }

                zipOut.close();
                return file.getPath();

            } catch (FileNotFoundException e) {
                file.delete();
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if (file.length() == 0) {
                    file.delete();
                }
            }
        }
        return null;
    }
    @Override
    public File createZip(String date, String fileName) throws Exception {
        File dir = new File(basePath, date);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(dir, fileName);

        if (!file.exists()) {
            file.createNewFile();
        }

        return file;

    }

POST方式

    @RequestMapping(value = "/zipp", method = RequestMethod.POST)
    public ResponseObj<String> getZipp(@RequestBody List<Long> fileIds, HttpServletResponse response) throws
            Exception {

//        response.setContentType("application/octet-stream");
//        response.setHeader("Cache-Control", "max-age=604800");
//        // 如果输出的是中文名的文件,在此处就要用URLEncoder.encode方法进行处理
//        String name = "生成zip文件";
//        String fileName = new String(name.getBytes(), "ISO-8859-1");
//        response.setHeader("Content-Disposition", String.format("attachment;filename=\"%s\"", fileName));

        String fileName = "生成zip文件";
        List<FileModel> fileModelList = fileService.selectList(new EntityWrapper<FileModel>().in("FILE_ID", fileIds));
        String path = fileService.downloadZipFile(fileName, fileModelList, response.getOutputStream());
        return new ResponseObj<>(path, RetCode.SUCCESS);
    }
    /**
     * 创建空zip,然后往zip中写入文件
     * @param fileName
     * @param fileModelList
     * @param outputStream
     * @return
     */
    public String downloadZipFile(String fileName, List<FileModel> fileModelList, OutputStream outputStream) {

        if (fileModelList.size() > 0) {
            File file = null;

            try {

                Date now = new Date();
                java.text.DateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd");
                //按照时间来分文件夹
                String dateString = format.format(now);
                fileName = fileName + "-" + IdWorker.getId() + ".zip";

                file = fileOperation.createZip(dateString, fileName);

                // 创建文件输出流
                FileOutputStream fous = new FileOutputStream(file);
                ZipOutputStream zipOut = new ZipOutputStream(fous);
//                //这种方式是浏览器默认下载方式,返回的io流给前端
//                ZipOutputStream zipOut = new ZipOutputStream(outputStream);

                for (FileModel fileModel : fileModelList) {
                    InputStream inputStream = fileOperation.downFile(fileModel.getFilePath().substring(7), fileModel
                            .getFileName());
                    FileUtils.zipFile(inputStream, zipOut, fileModel.fileOriginName + "." + fileModel.getFileType());
                    inputStream.close();
                }

                zipOut.close();
                return file.getPath();

            } catch (FileNotFoundException e) {
                file.delete();
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if (file.length() == 0) {
                    file.delete();
                }
            }
        }
        return null;
    }

LocalFileOperation

//所有的path必须以斜杠结束
@Component
public class LocalFileOperation implements IUploadFileOperation {


    @Value("${frame.upload.basePath}")
    protected String basePath;


    @Override
    public void createFile(String date, String fileName, MultipartFile inputStream) throws Exception {
        File dir = new File(basePath, date);

        if (!dir.exists()) {
            dir.mkdirs();
        }

        File file = new File(dir, fileName);

        if (!file.exists()) {
            file.createNewFile();
        }

        if (file.isFile()) {
            inputStream.transferTo(file);
        } else {
            throw new Exception("路径错误");
        }
    }


    @Override
    public InputStream downFile(String path, String fileName) throws FileNotFoundException {
        File dir = new File(basePath, path);
        File file = new File(dir, fileName);
        if (file.exists()) {
            return new FileInputStream(file);
        }
        throw new FileNotFoundException("待压缩文件 [" + fileName + "]不存在.");
    }

    @Override
    public void deleteFile(String path, String fileName) {
        try {
            File dir = new File(basePath, path);
            File file = new File(dir, fileName);
            file.delete();
        } catch (Exception ex) {

        }
    }

    @Override
    public File createZip(String date, String fileName) throws Exception {
        File dir = new File(basePath, date);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(dir, fileName);

        if (!file.exists()) {
            file.createNewFile();
        }

        return file;

    }


}
上一篇下一篇

猜你喜欢

热点阅读