隨筆-124  評論-49  文章-56  trackbacks-0

          文件下載代碼(2008-02-26 21:33:36)標簽:情感   
           
           String fileName = request.getParameter("fileName");
            fileName = fileName.substring(fileName.indexOf("=")+1);
           
            String filePath = servlet.getServletContext().getRealPath("")
            + "\\upload\\" ;
            String file = filePath + fileName;
            System.out.println(file);
            FileInputStream fis = null;
            OutputStream os = null; 


            byte[] bos = new byte[1024];
            int length = 0;
            try {

             response.setContentType("application/x-msdownload");
             response.setHeader("Content-disposition", "attachment;filename="
               + new String(fileName.getBytes("gb2312"),"iso8859-1"));
            
             fis = new FileInputStream(file);
             os = response.getOutputStream();
             while((length=fis.read(bos))!=-1){
              os.write(bos, 0, length);
          //    os.flush();
             }
            } catch (Exception e) {
             e.printStackTrace();
            }finally{
             try {
              if(os!=null)
               os.close();
              if(fis!=null)
               fis.close();
             } catch (Exception e) {
              e.printStackTrace();
             }
            }

           

           

           

           

           

          注意:

          1.response.setContentType("application/x-msdownload");

          2.response.setHeader("Content-disposition", "attachment;filename="
               + new String(fileName.getBytes("gb2312"),"iso8859-1"));

           PS:解決下載中文亂碼 fileName.getBytes("gb2312"),"iso8859-1")

          3.待解決問題:選擇圖片下載時候點取消拋異常

           

          ----------------------------------------------------------------------------------------------
          用commons.fileupload實現文件的上傳和下載2008年04月11日 星期五 15:27commons.fileupload實現文件的上傳,需要用到的組件如下:

          1)Commons-fileupload-1.1.zip,下載地址為http://archive.apache.org/dist/jakarta/commons/fileupload/

          2)commons-io-1.1.zip,下載地址為:http://archive.apache.org/dist/jakarta/commons/io/

          代碼如下:
          <%!
          //服務器端保存上傳文件的路徑
              String saveDirectory = "g:\\upload\\";
              // 臨時路徑 一旦文件大小超過getSizeThreshold()的值時數據存放在硬盤的目錄
              String tmpDirectory = "g:\\upload\\tmp\\";
              // 最多只允許在內存中存儲的數據大小,單位:字節
              int maxPostSize = 1024 * 1024;
          %>
          <%
              // 文件內容
              String FileDescription = null;
              // 文件名(包括路徑)
              String FileName = null;
              // 文件大小
              long FileSize = 0;
              // 文件類型
              String ContentType = null;

          %>

          <%
             DiskFileUpload fu = new DiskFileUpload();//創建一個新的文件上傳句柄
              // 設置允許用戶上傳文件大小,單位:字節
             fu.setSizeMax(200*1024*1024);
              // 設置最多只允許在內存中存儲的數據,單位:字節
             fu.setSizeThreshold(maxPostSize);
              // 設置一旦文件大小超過getSizeThreshold()的值時數據存放在硬盤的目錄
             fu.setRepositoryPath("g:\\upload\\tmp\\");
              //開始讀取上傳信息 得到所有文件
             try{
                List fileItems = fu.parseRequest(request);//解析上傳的請求
               }catch(FileUploadException e){
                   //這里異常產生的原因可能是用戶上傳文件超過限制、不明類型的文件等
                   //自己處理的代碼
               }
          %>
          <%
          // 依次處理每個上傳的文件
             Iterator iter = fileItems.iterator();
             while (iter.hasNext()) {
               FileItem item = (FileItem) iter.next();
                 //忽略其他不是文件域的所有表單信息
               if (!item.isFormField()) {
                 String name = item.getName();
                 long size = item.getSize();
                 String contentType = item.getContentType();
               if((name==null||name.equals("")) && size==0)
                 continue;
          %>
          <%
             //保存上傳的文件到指定的目錄
          String[] names=StringUtils.split(name,"\\"); //對原來帶路徑的文件名進行分割
             name = names[names.length-1];
             item.write(new File(saveDirectory+ name));
          }
          }
          %>
          下面是其簡單的使用場景:
          A、上傳項目只要足夠小,就應該保留在內存里。
          B、較大的項目應該被寫在硬盤的臨時文件上。
          C、非常大的上傳請求應該避免。
          D、限制項目在內存中所占的空間,限制最大的上傳請求,并且設定臨時文件的位置。

          可以根據具體使用用servlet來重寫,具體參數配置可以統一放置到一配置文件


          --------------------------------------------------------------------------------

          文件的下載用servlet實現
                public void doGet(HttpServletRequest request,
                                 HttpServletResponse response)
               {
                  String aFilePath = null;    //要下載的文件路徑
                   String aFileName = null;    //要下載的文件名
                   FileInputStream in = null; //輸入流
                   ServletOutputStream out = null; //輸出流

                   try
              {
                  
                       aFilePath = getFilePath(request);
                       aFileName = getFileName(request);

                       response.setContentType(getContentType(aFileName) + "; charset=UTF-8");
                       response.setHeader("Content-disposition", "attachment; filename=" + aFileName);

                       in = new FileInputStream(aFilePath + aFileName); //讀入文件
                      out = response.getOutputStream();
                      out.flush();
                     int aRead = 0;
                     while((aRead = in.read()) != -1 & in != null)
                 {
                       out.write(aRead);
                   }
                     out.flush();
                }
                 catch(Throwable e)
               {
               log.error("FileDownload doGet() IO error!",e);
                }
                   finally
                   {
                       try
                       {
                           in.close();
                           out.close();
                       }
                       catch(Throwable e)
                       {
                       log.error("FileDownload doGet() IO close error!",e);
                       }
                   }
               }

          posted on 2009-11-29 21:35 junly 閱讀(253) 評論(0)  編輯  收藏 所屬分類: java
          主站蜘蛛池模板: 上思县| 丰宁| 金华市| 信阳市| 青浦区| 新宁县| 津南区| 黎平县| 介休市| 泰兴市| 宝清县| 平顺县| 宁城县| 河间市| 鲜城| 翁牛特旗| 三江| 镇巴县| 惠州市| 洞头县| 阜新| 文昌市| 桦南县| 游戏| 新蔡县| 苏尼特左旗| 昔阳县| 开阳县| 新沂市| 海口市| 彰化市| 荆州市| 龙州县| 永寿县| 岢岚县| 拜泉县| 连云港市| 成武县| 湘潭县| 犍为县| 万宁市|