簡易代碼之家

            BlogJava :: 首頁 :: 聯系 :: 聚合  :: 管理
            157 Posts :: 2 Stories :: 57 Comments :: 0 Trackbacks

          Jsp中文件下載的處理

          有些人直接把要下載的文件放在項目web下面的虛擬路徑下,然后提供鏈接下載,這種處理對客戶端的要求比較高,要求客戶機器上必須有要下載的文件類型才可以,沒有的話下載下來的數據是亂的。客戶端查看自己電腦上的文件類型,比如xp系統,打開一個文件夾,菜單中,工具,文件夾選項,文件類型,針對某個文件類型可以查看高級中的配置。另一種就是用流來進行下載,簡單代碼如下:

          public ActionForward downloadFile(ActionMapping mapping, ActionForm form,
                      HttpServletRequest request, HttpServletResponse response)
                      
          throws Exception {
                  BufferedInputStream bis 
          = null;
                  BufferedOutputStream bos 
          = null;
                  OutputStream fos 
          = null;
                  InputStream fis 
          = null;

                  File downloadFile 
          = null;
                  String dmpFolder 
          = request.getSession().getServletContext()
                          .getRealPath(
          "")
                          
          + "\\files\\downloads\\";
                  File folder 
          = new File(dmpFolder);
                  File[] files 
          = folder.listFiles();
                  String fileName 
          = request.getParameter("fileName");
                  
          for (int i = 0; i < files.length; i++{
                      
          if (files[i].getName().equals(fileName)) {
                          downloadFile 
          = files[i];
                          
          break;
                      }

                  }

                  fis 
          = new FileInputStream(downloadFile);
                  bis 
          = new BufferedInputStream(fis);
                  fos 
          = response.getOutputStream();
                  bos 
          = new BufferedOutputStream(fos);
                  response.setHeader(
          "Content-disposition""attachment;filename="
                          
          + URLEncoder.encode(fileName, "utf-8"));
                  
          int bytesRead = 0;
                  
          byte[] buffer = new byte[8192];
                  
          while ((bytesRead = bis.read(buffer, 08192)) != -1{
                      bos.write(buffer, 
          0, bytesRead);
                  }

                  bos.flush();
                  fis.close();
                  bis.close();
                  fos.close();
                  bos.close();
                  
          return null;
              }
          posted on 2010-06-08 18:16 Jakin.zhou 閱讀(188) 評論(0)  編輯  收藏

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 丹凤县| 翁源县| 黔西县| 清河县| 隆化县| 永靖县| 玉溪市| 阜阳市| 云梦县| 江津市| SHOW| 平阳县| 新民市| 织金县| 南雄市| 娄底市| 松滋市| 驻马店市| 商丘市| 阿鲁科尔沁旗| 浑源县| 长宁区| 乌鲁木齐市| 当雄县| 新泰市| 手游| 菏泽市| 民丰县| 兴文县| 巨鹿县| 东阿县| 雷波县| 镇宁| 福建省| 钦州市| 江口县| 白朗县| 紫阳县| 马关县| 蕉岭县| 太康县|