浏览器+批量下载文件

最近,在项目中遇到了需要将一系列的图片打包下载的需求,借鉴了网上的一些通用方法,就顺便分享出来实现的方法,不太记得借鉴的是哪位兄弟的博客了,总之万分感谢,进入正题,实现打包下载的基本功能:

1.controller层代码:

/**
     * 图片压缩打包
     */
    @RequestMapping(value = "/zipFile")
    public void compressionFile(HttpServletRequest request, HttpServletResponse response,String busiId) throws Exception{
        //业务代码,根据前台传来的ID查询到资源表的图片list
        SubMetaData subMetaData = subMetaDataService.findByBusiId(busiId);
        if (subMetaData != null) {
            List<SubMetaDataAtt> list = subMetaDataAttService.findByDataId(subMetaData.getDataId());
            if (list.size() > 0){
                subMetaDataAttService.downloadAllFile(request,response,list);
            }
        }
    }

 2.service层通用的文件打包下载

/**
     * 将多个文件进行压缩打包,解决文件名下载后的乱码问题
     *
     */
    public void downloadAllFile(HttpServletRequest request, HttpServletResponse response, List<SubMetaDataAtt> list) throws UnsupportedEncodingException{
        String downloadName = "附件图片.zip";
        String userAgent = request.getHeader("User-Agent");
        // 针对IE或者以IE为内核的浏览器:
        if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            downloadName = java.net.URLEncoder.encode(downloadName, "UTF-8");
        } else {
            // 非IE浏览器的处理:
            downloadName = new String(downloadName.getBytes("UTF-8"), "ISO-8859-1");
        }
//经过上面的名称处理即可解决文件名下载后乱码的问题
        response.setContentType("multipart/form-data");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition",  String.format("attachment; filename=\"%s\"", downloadName));
        //response.setHeader("Content-Disposition", "attachment;fileName=" + downloadName);
        OutputStream outputStream = null;
        ZipOutputStream zos = null;
        try {
            outputStream = response.getOutputStream();
            zos = new ZipOutputStream(outputStream);
            // 将文件流写入zip中,此方法在下面贴出
            downloadTolocal(zos,list);
        } catch (IOException e) {
            logger.error("downloadAllFile-下载全部附件失败",e);
        }finally {
            if(zos != null) {
                try {
                    zos.close();
                } catch (Exception e2) {
                    logger.info("关闭输入流时出现错误",e2);
                }
            }
            if(outputStream != null) {
                try {
                    outputStream.close();
                } catch (Exception e2) {
                    logger.info("关闭输入流时出现错误",e2);
                }
            }
        }
    }

3.前台js的请求方法:

注:文件的下载不要使用AJAX请求的方法,这样是无法响应请求的,一般会采用Window.open的方法。

window.open(context+"/sub/submetadataatt/zipFile?busiId="+downloadId);//这里的downloadId是我需要传到后台的变量。

总结:关于上传,下载的操作,实际上是要对于java的IO十分熟悉,才可以玩的转,大家一定要把握好基础才可以在项目中游刃有余,不像我需要去借鉴他人的东西,大家一起努力,加油!

详细的配置信息可以参考我写的这篇文章:http://blog.ncmem.com/wordpress/2019/08/28/java%e6%89%b9%e9%87%8f%e4%b8%8b%e8%bd%bd/ 

猜你喜欢

转载自www.cnblogs.com/songsu/p/11424621.html