首页 > 编程 > Java > 正文

java浏览器文件打包下载过程解析

2019-11-26 08:24:37
字体:
来源:转载
供稿:网友

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

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的IO十分熟悉,才可以玩的转,大家一定要把握好基础才可以在项目中游刃有余,不像我需要去借鉴他人的东西,大家一起努力,加油!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表