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("下载成功");

    }

 

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

    }

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值