java 文件上傳顯示進度

chyx413332087 13年前發布 | 6K 次閱讀
       實現功能:通過在頁面中上傳文件,到ftp服務器
       頁面用得html標簽  <input type="file"/>  在表單中,設置 表單,請求文件頭,enctype="multipart/form-data",我用得apache fileUpload,結合 apache Ftp  ,代碼很簡單,網上到處都有,但是有點注意, fileUpload,是會再web服務器,創建一個temp目錄,將文件讀到臨時目錄,如果不顯示設置臨時目錄,會再web服務器目錄,也可以自己顯示設置臨時目錄,   apache ftp 實際是讀取臨時目錄流,到指定的 ftp 服務器主機地址,原來找了很多資料,想知道如何搞進度條,原來 在 apache fileUploade,有個監聽器,可以監聽 流每次讀取的文件信息, org.apache.commons.fileupload。
/* pBytesRead  到目前為止讀取文件的比特數
  * pContentLength 文件總大小
  * pItems 目前正在讀取第幾個文件
  */
public interface ProgressListener {
 public abstract void update(long pBytesRead  , long pContentLength , int i);
}
implement  這個接口,
在文件上傳的時候
ServletFileUpload upload = new ServletFileUpload(factory);
   progressListen getBarListener = new progressListen(request);
   upload.setProgressListener(getBarListener);
有個問題一定要注意 ,一定要寫在   ServletFileUpload   初始對象后面,不然,會讀不到數據,這個要看源代碼就知道,在upload.write()里面,有對getBarListener !=null 的判斷,因此要寫在 初始對象后面,我為這個事,發了不少的實際,
在頁面方面,需要搞個ajax ,調用一個請求,請求里面能讀取 到getBarListener   里面的update(),設置的數據,  用個windows.setTimeOut(,5000),不斷調用,不能太快,太快的話,頁面基本是白色的,反應不過來
2:上面用windows.setTimeOut實時性不是很強,但是如果要狠強的實時性,可以采用服務器推得技術,由服務器主動發現客戶端,這就要去研究了哦, 
3:在html5  下解決就很容易了,html5是雙工通信,長連接的
  下面是簡易代碼:
   
public class progressListen   implements ProgressListener {
    private HttpSession session;
 
   public progressListen(HttpServletRequest request)
   {
  this.session=request.getSession();
  this.session.setAttribute("fileAttr", "ttttttttttttt");
  
 
  
   }
 
 /* pBytesRead  到目前為止讀取文件的比特數
  * pContentLength 文件總大小
  * pItems 目前正在讀取第幾個文件
  */
 public void update(long pBytesRead, long pContentLength, int pItems) {
 
 
  
  session.setAttribute("byte", String.valueOf(pBytesRead));
  session.setAttribute("pContentLength", String.valueOf(pContentLength));
  
  System.out.println("update="+String.valueOf(pBytesRead));
 }
}

public class ProgressServlet extends HttpServlet {
 /**
  * Constructor of the object.
  */
 public ProgressServlet() {
  super();
 }
 /**
  * Destruction of the servlet. <br>
  */
 public void destroy() {
  super.destroy(); // Just puts "destroy" string in log
  // Put your code here
 }
 /**
  * The doGet method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to get.
  *
  * @param request the request send by the client to the server
  * @param response the response send by the server to the client
  * @throws ServletException if an error occurred
  * @throws IOException if an error occurred
  */
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //response.setContentType("text/html");
  System.out.println("id="+request.getSession().getId());
  
  System.out.println("isNew="+request.getSession().isNew());
  
  PrintWriter out = response.getWriter();
  
 
  String b=(String)request.getSession().getAttribute("byte");
  String pContentLength=(String)request.getSession().getAttribute("pContentLength");
  String fileAttr=(String)request.getSession().getAttribute("fileAttr");
  
  System.out.println("bbb="+b);
  System.out.println("1212=="+pContentLength);
   
  out.println("<HTML>");
  out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
  out.println("  <BODY>");
  out.println(request.getSession().getId());
   out.println(fileAttr);
   out.println("bb="+b);
   out.println("1212="+pContentLength);
      out.println("  </BODY>");
  out.println("</HTML>");
  out.flush();
  out.close();
 }
 /**
  * The doPost method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to post.
  *
  * @param request the request send by the client to the server
  * @param response the response send by the server to the client
  * @throws ServletException if an error occurred
  * @throws IOException if an error occurred
  */
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
            this.doGet(request, response);
 }
 /**
  * Initialization of the servlet. <br>
  *
  * @throws ServletException if an error occurs
  */
 public void init() throws ServletException {
  // Put your code here
 }
}
 
public class UploadFileAction extends HttpServlet {
 /**
  * Constructor of the object.
  */
 public UploadFileAction() {
  super();
 }
 /**
  * Destruction of the servlet. <br>
  */
 public void destroy() {
  super.destroy(); // Just puts "destroy" string in log
  // Put your code here
 }
 /**
  * The doGet method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to get.
  *
  * @param request the request send by the client to the server
  * @param response the response send by the server to the client
  * @throws ServletException if an error occurred
  * @throws IOException if an error occurred
  */
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
 
    response.reset();
  
 // response.setContentType("text/html"); application/octet-stream
       response.setContentType("application/x-download");
 // response.setContentType("application/octet-stream");
  
  
  
  String file_name=request.getParameter("file_name");
  
  System.out.println("file_name="+file_name);
  //response.setHeader("Content-Disposition","attachment;filename=" + file_name); 
 // response.addHeader("Content-Disposition","attachment;filename=" + file_name); 
  
  //加上下面的這句話,下載下來的圖片,打開為空白,當是大小一樣
  response.setHeader("Content-Disposition", "attachment;filename=\"" + file_name + "\"" );
  //response.setHeader("Cache-Control", "private");
   //setHeader("Cache-Control", "private");
  java.io.File  ff=new File("F:/java/apache-ftpserver-1.0.5/res/home/"+file_name);
  //構建下載文件的對象
 
      //獲得文件的長度
  long filesize = ff.length();
      //設置輸出格式
  //response.addHeader("content-type", "application/x-msdownload;");
  //response.addHeader("Content-Disposition", "attachment; filename=" + response.encodeURL(file_name));
    response.addHeader("content-length", Long.toString(filesize));
  //System.out.println("ssss="+ff.getAbsolutePath());
  //System.out.println("ssss="+ff.isFile());
  
 
 
  FTPClient  ftpClient=new FTPClient();
  ftpClient.connect("127.0.0.1", 2121);
  ftpClient.login("admin", "admin");
  ftpClient.enterLocalPassiveMode(); 
  ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
  ftpClient.addProtocolCommandListener(new PrintCommandListener(
                new PrintWriter(System.out)));
  FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);  
        conf.setServerLanguageCode("zh");
     OutputStream outputStream=response.getOutputStream();
   
        boolean b = ftpClient.retrieveFile(file_name, outputStream);
     
     if(b)
      System.out.println("下載成功!");
     else
      System.out.println("下載失敗!");
     outputStream.flush();
     outputStream.close();
  //FTPFile ftpFile=ftpClient.mlistFile(file_name);
 // System.out.println("ftpFile.isFile="+ftpFile.isFile());
      //  java.io.File  f=new File(file_name);
 // java.io.OutputStream  file=new FileOutputStream(f);
     //   System.out.println(ftpClient.printWorkingDirectory());
       
 //java.io.InputStream  input= ftpClient.retrieveFileStream(file_name);
          /*
  java.io.InputStream  input =new FileInputStream(ff);
     byte r[]=new byte[1024];
  OutputStream outputStream=response.getOutputStream();
         int c=-1;
        
  while((c=input.read(r))>0)
  {
   outputStream.write(r, 0, c);
  }
  outputStream.flush();
  
  
   outputStream.close();
   input.close();
   response.flushBuffer();
   */
  // response.sendRedirect("index.jsp");
  // outputStream.close();
   
   
  
  
  /*
  
  boolean b =ftpClient.retrieveFile(file_name, file);
  
     if(b)
      System.out.println("下載成功!");
     else
      System.out.println("下載失敗!");
  */  
    
    //file.flush();
     //file.close();
    // response.flushBuffer();
    
  //outputStream.flush();
  
   
    // file.flush();
     //file.close();
    // ftpClient.logout();
     //ftpClient.disconnect();
     //outputStream.close();
     // response.flushBuffer();
  
 }
 /**
  * The doPost method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to post.
  *
  * @param request the request send by the client to the server
  * @param response the response send by the server to the client
  * @throws ServletException if an error occurred
  * @throws IOException if an error occurred
  */
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
 // response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  response.setCharacterEncoding("GBK");
  out.println("uri="+request.getRequestURI());
  out.println("url="+request.getRequestURL());
  
  
  
  try
  {
  boolean   isMult=ServletFileUpload.isMultipartContent(request);
  if(isMult==true)  //說明是
  {
   DiskFileItemFactory  factory = new DiskFileItemFactory();
   ServletFileUpload upload = new ServletFileUpload(factory);
   progressListen getBarListener = new progressListen(request);
   upload.setProgressListener(getBarListener);
   
   List<FileItem> items = upload.parseRequest(request);  
   Iterator<FileItem> itr = items.iterator();   
   while (itr.hasNext()) {        
    FileItem item = (FileItem) itr.next(); 
    
    //檢查當前項目是普通表單項目還是上傳文件。       
    if (item.isFormField()) {
     //如果是普通表單項目,顯示表單內容。 
     String fieldName = item.getFieldName();
     if (fieldName.equals("name"))
                          out.println("ssssss="+fieldName);     
     }
    else {  //如果是上傳文件,顯示文件名。   
      
     out.print("<br>");  
     
     File fullFile = new File(item.getName());
     
     out.print("<br>="+fullFile.getName()); 
     
     out.print("lujin="+fullFile.getAbsolutePath());
     
     out.print("<br>111="+fullFile.getPath());
     
    // item.write(fullFile);
     
     FTPClient  ftpClient=new FTPClient();
     
     ftpClient.connect("127.0.0.1", 2121);
     ftpClient.login("admin", "admin");
     out.print(ftpClient.getRemotePort());
     ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
     ftpClient.setControlEncoding("GBK");
     ftpClient.addProtocolCommandListener(new PrintCommandListener(
                              new PrintWriter(System.out)));
     //out.println(ftpClient.getReplyCode());
     //設置上傳工作目錄   不設置,默認 res\home
     //ftpClient.changeWorkingDirectory("/");     
    // FileInputStream  fileInputStream=new FileInputStream(fullFile);
     String newFileName="test_"+new Random().nextInt(10000)+".JPG";
       ftpClient.storeFile(newFileName,item.getInputStream());
     
       ftpClient.logout();
       ftpClient.disconnect();
       
       //上傳的文件名
       out.print("the upload file name is " + newFileName);  
      // downFile(newFileName,out);
     }
    } 
   }
  }catch(Exception e)
  {
  e.printStackTrace(); 
  }
 }
 
 
 
 
 public void downFile(String remoteFileName,PrintWriter out ) throws Exception
 {
 
  FTPClient  ftpClient=new FTPClient();
  ftpClient.connect("127.0.0.1", 2121);
  ftpClient.login("admin", "admin");
  ftpClient.addProtocolCommandListener(new PrintCommandListener(
                new PrintWriter(System.out)));
  ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
  String fileName[]=ftpClient.listNames();
  
  java.io.File f=new File(".\\"+fileName[4]);
  System.out.println("本地路徑="+f.getAbsolutePath());
  
    java.io.OutputStream  file=new FileOutputStream("./"+fileName[4]);
   file.flush();
  boolean b=ftpClient.retrieveFile("test_4258.jpeg", file);
  
    if(b)
     System.out.println("成功!");
    else
     System.out.println("失敗!");
  
  file.flush();
  ftpClient.logout();
  ftpClient.disconnect();
  file.close();
  for (int i=0;i<fileName.length;i++)
  {out.println("<br>"); 
   out.println("fileName="+fileName[i]);
  }  
 }
 
 /**
  * Initialization of the servlet. <br>
  *
  * @throws ServletException if an error occurs
  */
 public void init() throws ServletException {
  // Put your code here
 }
}
 
<script type="text/javascript">
  function getBarPress()
  {
   var request=new XMLHttpRequest();
     var sendUrl="http://127.0.0.1:8080/webTest/servlet/ProgressServlet";
   request.open("GET", sendUrl);      
         request.onreadystatechange = function() {
                    if (request.readyState == 4) {
                        if (request.status == 200){
                          document.getElementById("forecasts").innerHTML = request.responseText;
                        }
                    //   getBarPress();
                    }
                };
                request.send(null);
               
       /**
 if(request.readyState==4)
 {
     if(request.status==200)
    {    
     alert(request.responseText);
    document.getElementById("xianShi").innerHTML = request.responseText;
       }    
 }
 
  request.send(null);
  **/
 
 
 window.setTimeout("getBarPress()",4000);
  }
 
  function  onbuttommit()
 {
    var formid=document.getElementById("uploadForm");
 formid.submit();
 
 window.setTimeout("getBarPress()", 7000);
 }
 
 </script>
 
 
 
 
 
 
 
 
 
 本文由用戶 chyx413332087 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!