溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

java中瀏覽器文件打包下載的示例分析

發(fā)布時(shí)間:2021-07-20 13:45:52 來源:億速云 閱讀:159 作者:小新 欄目:編程語言

這篇文章主要介紹java中瀏覽器文件打包下載的示例分析,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

1.controller層代碼:

/**
   * 圖片壓縮打包
   */
  @RequestMapping(value = "/zipFile")
  public void compressionFile(HttpServletRequest request, HttpServletResponse response,String busiId) throws Exception{
    //業(yè)務(wù)代碼,根據(jù)前臺(tái)傳來的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層通用的文件打包下載

/**
   * 將多個(gè)文件進(jìn)行壓縮打包,解決文件名下載后的亂碼問題
   *
   */
  public void downloadAllFile(HttpServletRequest request, HttpServletResponse response, List<SubMetaDataAtt> list) throws UnsupportedEncodingException{
    String downloadName = "附件圖片.zip";
    String userAgent = request.getHeader("User-Agent");
    // 針對IE或者以IE為內(nèi)核的瀏覽器:
    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");
    }
//經(jīng)過上面的名稱處理即可解決文件名下載后亂碼的問題
    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("關(guān)閉輸入流時(shí)出現(xiàn)錯(cuò)誤",e2);
        }
      }
      if(outputStream != null) {
        try {
          outputStream.close();
        } catch (Exception e2) {
          logger.info("關(guān)閉輸入流時(shí)出現(xiàn)錯(cuò)誤",e2);
        }
      }

    }

  }

將文件寫入zip中的方法:

private void downloadTolocal(ZipOutputStream zos, List<SubMetaDataAtt> list) throws IOException {
    //獲取文件信息//此處為業(yè)務(wù)代碼,可根據(jù)自己的需要替換,我在這里是將資源表list循環(huán)出取得路徑以及文件名,然后放進(jìn)ZipEntry中再執(zhí)行下載。
    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;
      //創(chuàng)建zip實(shí)體(一個(gè)文件對應(yīng)一個(gè)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);
        //文件流循環(huán)寫入ZipOutputStream
        while ((len = in.read(buffer)) != -1 ) {
          zos.write(buffer, 0, len);
        }
      } catch (Exception e) {
        logger.info("下載全部附件--壓縮文件出錯(cuò)",e);
      }finally {
        if(entry != null) {
          try {
            zos.closeEntry();
          } catch (Exception e2) {
            logger.info("下載全部附件--zip實(shí)體關(guān)閉失敗",e2);
          }
        }
        if(in != null) {
          try {
            in.close();
          } catch (Exception e2) {
            logger.info("下載全部附件--文件輸入流關(guān)閉失敗",e2);
          }
        }
        if(is != null) {
          try {
            is.close();
          }catch (Exception e) {
            logger.info("下載全部附件--輸入緩沖流關(guān)閉失敗",e);
          }
        }


      }

    }

3.前臺(tái)js的請求方法:

注:文件的下載不要使用AJAX請求的方法,這樣是無法響應(yīng)請求的,一般會(huì)采用Window.open的方法。

window.open(context+"/sub/submetadataatt/zipFile?busiId="+downloadId);//這里的downloadId是我需要傳到后臺(tái)的變量。

以上是“java中瀏覽器文件打包下載的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI