• java压缩下载图片并以zip流的形式下载到客户端


        /**
         * 
         * @param page
         * @param rows
         * @param works
         * @return
         * @author ffwwzz 下载zip
         * @throws IOException
         * @throws InterruptedException
         */
        @RequestMapping("/download")
        @ResponseBody
        public CommonResult download(HttpServletRequest req, HttpServletResponse res)
                throws IOException, InterruptedException {
            List<Works> urls = service.selectPictures();
            // List<String> urls = service.selectPictures1();
            return new CommonResult().success("下载成功");
    
        }
    package com.sm.ayz.springcloud.aop;
    
    import java.io.IOException;
    import java.util.List;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.annotation.AfterReturning;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Pointcut;
    import org.springframework.stereotype.Component;
    import org.springframework.web.context.request.RequestContextHolder;
    import org.springframework.web.context.request.ServletRequestAttributes;
    
    import com.sm.ayz.springcloud.bean.works.Works;
    import com.sm.ayz.springcloud.utils.FileUtil;
    
    /**
     * 业务切面
     */
    @Aspect
    @Component
    public class DownloadAop {
    
        @Pointcut("@annotation(com.sm.ayz.springcloud.annotation.Download)")
        public void logCut() {
        }
    
        @AfterReturning(returning = "rvt", pointcut = "logCut()")
        public void after(JoinPoint jp, Object rvt) throws IOException, InterruptedException {
            @SuppressWarnings("unchecked")
            List<Works> list = (List<Works>) rvt;
    
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                    .getRequest();
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                    .getResponse();
            FileUtil.download(request, response, list);
    
            System.out.println("方法最后执行.....");
        }
    
    }
    @Override
        @Download
        public List<Works> selectPictures() {
            return baseMapper.selectPictures();
        }
    package com.sm.ayz.springcloud.utils;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.List;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.google.gson.Gson;
    import com.google.gson.reflect.TypeToken;
    import com.sm.ayz.springcloud.bean.WorkJsonEntity;
    import com.sm.ayz.springcloud.bean.works.Works;
    
    public class FileUtil {
    
    /**
         * 下载并压缩
         * 
         * @param request
         * @param response
         * @param urls
         * @author ffwwzz
         * @throws IOException
         * @throws InterruptedException
         */
        public static boolean download(HttpServletRequest request, HttpServletResponse response, List<Works> worksList)
                throws IOException, InterruptedException {
            String downloadFilename = "用户作品收录记录" + DateFormatTreadLocal.df.get().format(new Date()) + ".zip";// 文件的名称
            downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");// 转换中文否则可能会产生乱码
            response.setContentType("application/octet-stream");// 指明response的返回对象是文件流
            response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);// 设置在下载框默认显示的文件名
            ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
            dozip.download(worksList, zos);
            DateFormatTreadLocal.df.remove();
            zos.flush();
            zos.close();
            return true;
        }
    
        /**
         * 
         * @author fwz 静态工厂类,避免多线程工作数据读取失败
         *
         */
        static class DateFormatTreadLocal {
    
            private static ThreadLocal<SimpleDateFormat> df = new ThreadLocal<SimpleDateFormat>() {
                @Override
                protected SimpleDateFormat initialValue() {
                    return new SimpleDateFormat("yyyy-MM-dd");
                }
            };
        }
    
        static class dozip {
    
            public dozip() {
            }
    
            public static void download(List<Works> worksList, ZipOutputStream zos) throws IOException {
                SimpleDateFormat sdf = DateFormatTreadLocal.df.get();
                for (int i = 0; i < worksList.size(); i++) {
                    if (worksList.get(i).getWorksType() != null) {
    
                        if (worksList.get(i).getWorksType() == 0) {
    
                            if (StringUtils.isNotEmpty(worksList.get(i).getPicture())
                                    && worksList.get(i).getPicture().indexOf("http://") != -1) {
                                String[] urls = worksList.get(i).getPicture().split(",");
                                for (int j = 0; j < urls.length; j++) {
    
                                    URL url = new URL(urls[j]);
                                    zos.putNextEntry(new ZipEntry(worksList.get(i).getTitle() + "-" + j
                                            + sdf.format(worksList.get(i).getIncludedTime()) + String.format("%02d", i)
                                            + ".jpg"));
                                    // FileInputStream fis = new FileInputStream(new File(files[i]));
                                    InputStream fis = url.openConnection().getInputStream();
                                    byte[] buffer = new byte[1024];
                                    int r = 0;
                                    while ((r = fis.read(buffer)) != -1) {
                                        synchronized (zos) {
                                            zos.write(buffer, 0, r);
                                        }
                                    }
                                    fis.close();
    
                                }
                            }
                        }
    
                        if (worksList.get(i).getWorksType() == 2) { // 图文作品
    
                            if (StringUtils.isNotEmpty(worksList.get(i).getContent())
                                    && worksList.get(i).getContent().indexOf("http://") != -1) {
                                Gson gson = new Gson();
                                List<WorkJsonEntity> urls = gson.fromJson(worksList.get(i).getContent(),
                                        new TypeToken<List<WorkJsonEntity>>() {
                                        }.getType());
    
                                for (int j = 0; j < urls.size(); j++) {
    
                                    URL url = new URL(urls.get(j).getImage());
                                    zos.putNextEntry(new ZipEntry(worksList.get(i).getTitle() + "-" + j
                                            + sdf.format(worksList.get(i).getIncludedTime()) + String.format("%02d", i)
                                            + ".jpg"));
                                    // FileInputStream fis = new FileInputStream(new File(files[i]));
                                    InputStream fis = url.openConnection().getInputStream();
                                    byte[] buffer = new byte[1024];
                                    int r = 0;
                                    while ((r = fis.read(buffer)) != -1) {
                                        synchronized (zos) {
                                            zos.write(buffer, 0, r);
                                        }
                                    }
                                    fis.close();
    
                                }
                            }
                        }
                    }
                }
                System.out.println("fis---close");
            }
    
        }
    
    }
  • 相关阅读:
    python 给文件批量加‘“’ ”,"
    ubuntu 编译android 源码笔记
    ubuntu java 环境配置
    Android4.4r1(KitKat)源码下载地址
    android 学习视频汇总
    Java 注解
    Linux 索引节点(inode)详解
    系统启动
    Win7、Ubuntu双系统正确卸载Ubuntu系统
    深入理解LInux内核-进程通信
  • 原文地址:https://www.cnblogs.com/fengwenzhee/p/10876020.html
Copyright © 2020-2023  润新知