温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java中浏览器文件打包下载的示例分析

发布时间:2021-07-20 13:45:52 来源:亿速云 阅读:150 作者:小新 栏目:编程语言

这篇文章主要介绍java中浏览器文件打包下载的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

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

    }

  }

将文件写入zip中的方法:

private void downloadTolocal(ZipOutputStream zos, List<SubMetaDataAtt> list) throws IOException {
    //获取文件信息//此处为业务代码,可根据自己的需要替换,我在这里是将资源表list循环出取得路径以及文件名,然后放进ZipEntry中再执行下载。
    for (SubMetaDataAtt subMetaDataAtt : list) {
      String fileId = subMetaDataAtt.getAttId();
      String fileName = subMetaDataAtt.getFileAlias()+subMetaDataAtt.getFileSuffixName();
      String path = subMetaDataAtt.getFileAbsolutePath();
      InputStream is = null;
      BufferedInputStream in = null;
      byte[] buffer = new byte[1024];
      int len;
      //创建zip实体(一个文件对应一个ZipEntry)
      ZipEntry entry = new ZipEntry(fileName);
      try {
        //获取需要下载的文件流
        File file= new File(path);
        if(file.exists()){
          is = new FileInputStream(file);
        }
        in = new BufferedInputStream(is);
        zos.putNextEntry(entry);
        //文件流循环写入ZipOutputStream
        while ((len = in.read(buffer)) != -1 ) {
          zos.write(buffer, 0, len);
        }
      } catch (Exception e) {
        logger.info("下载全部附件--压缩文件出错",e);
      }finally {
        if(entry != null) {
          try {
            zos.closeEntry();
          } catch (Exception e2) {
            logger.info("下载全部附件--zip实体关闭失败",e2);
          }
        }
        if(in != null) {
          try {
            in.close();
          } catch (Exception e2) {
            logger.info("下载全部附件--文件输入流关闭失败",e2);
          }
        }
        if(is != null) {
          try {
            is.close();
          }catch (Exception e) {
            logger.info("下载全部附件--输入缓冲流关闭失败",e);
          }
        }


      }

    }

3.前台js的请求方法:

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

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

以上是“java中浏览器文件打包下载的示例分析”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI