我的漫漫程序之旅

          專注于JavaWeb開發(fā)
          隨筆 - 39, 文章 - 310, 評論 - 411, 引用 - 0
          數(shù)據(jù)加載中……

          JSP實現(xiàn)點擊鏈接后下載文件(相當于右鍵另存)功能

          /**
               * 實現(xiàn)文件另存功能
               * 
               * 
          @param text
               *            文件內容
               * 
          @param fileName
               *            文件名稱
               * 
          @return
               
          */

              
          protected String renderFile(String text, String fileName)
                      
          throws IOException
              
          {
                  response.addHeader(
          "Content-Disposition""attachment; filename="
                          
          + fileName);
                  response.setContentType(
          "application/octet-stream");
                  response.setCharacterEncoding(
          "GB2312");
                  response.getWriter().write(text);
                  response.flushBuffer();
                  response.getWriter().close();
                  
          return null;
              }


          下載的action:

          /**
               * 提供下載的方法
               * 
          @return
               
          */

              
          public String down()
              
          {
                  String dir 
          = getFullPath() + "/upload/file/";
                  
          try
                  
          {
                      
          if (!FileUtils.exists(dir))
                      
          {
                          
          new File(dir).mkdirs();
                      }

                      Random r 
          = new Random(System.currentTimeMillis());
                      Integer randomInt 
          = r.nextInt();
                      
          this.renderFile("test content:" + randomInt,randomInt + ".txt");
                  }

                  
          catch (IOException e)
                  
          {
                      e.printStackTrace();
                      
          this.renderText(e.getMessage());
                  }

                  
          return null;
              }

          頁面鏈接調用:
          <href="${ctx}/va/va!down.do" >下載</a>


          posted on 2009-07-01 15:59 々上善若水々 閱讀(3032) 評論(1)  編輯  收藏

          評論

          # re: JSP實現(xiàn)點擊鏈接后下載文件(相當于右鍵另存)功能  回復  更多評論   

          原來還有這么清晰的方法啊
          2009-07-02 22:03 | blackbat

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


          網(wǎng)站導航:
           
          主站蜘蛛池模板: 应城市| 长岭县| 和平县| 新龙县| 邹城市| 新丰县| 金平| 宁强县| 石阡县| 景东| 遂川县| 通山县| 武威市| 右玉县| 长宁区| 青州市| 新巴尔虎右旗| 宽甸| 江华| 南雄市| 喀喇沁旗| 浠水县| 丘北县| 宜阳县| 富阳市| 江城| 天柱县| 和顺县| 北碚区| 灵石县| 巫山县| 平安县| 来安县| 甘肃省| 同江市| 沂南县| 中山市| 武乡县| 阿拉善左旗| 秦皇岛市| 七台河市|