2011-05-19 37 views
1

斐伊川我用插座將文件上載到服務器,我需要加載文件的百分比?我該怎麼辦呢?我有maximun值即文件的長度,我怎麼能得到多少文件已上載?使用套接字上傳Java文件,需要上傳文件的百分比?

FileInputStream fis = new FileInputStream(fil); 
       BufferedInputStream in = new BufferedInputStream(fis); 
       BufferedOutputStream out = new BufferedOutputStream(skt.getOutputStream()); 

       //Write the file to the server socket   
       int i; 

       while ((i = in.read()) != -1) { 
        publishProgress(???); 
        out.write(i);     
        System.out.println(i); 
       } 

我需要在publishProgress方法中傳遞文件的長度。

+0

監聽者觀察圖形中讀出了。在這種情況下,PublishProgress可能會吐出一大堆所有被訂閱的監聽器。那時你有你的答案。 – MJB 2011-05-19 16:12:21

回答

1

使用緩衝複製

FileInputStream fis = new FileInputStream(fil); 
BufferedInputStream in = new BufferedInputStream(fis); 
BufferedOutputStream out = new BufferedOutputStream(skt.getOutputStream()); 

//Write the file to the server socket 
int i; 
int written = 0; 
byte[] buf = new byte[512]; 

while ((i = in.read(buff)) != -1) { 

    out.write(buff,0,i); 
    written += i; 
    publishProgress((double)written/length); 
    //passing a double value from 0-1 to say how much is transmitted (length is length of file) 
    System.out.println(buff+", "+i); 
} 
+0

哎使用您in.read(BUFF)我的上傳速度increased..thks一個lot..and你能PLZ解釋速度的原因增加了多少? – 2011-05-20 05:15:40

+2

因爲字節傳輸字節意味着你必須去通過它必須檢查每個字節是否結束的循環n次(n是文件的大小),是否具有的OutputStream沖洗和打印值。但使用像我顯示的緩衝區意味着最多512字節的塊通過循環,上述開銷不僅是一次prr塊 – 2011-05-20 11:57:21

0

下面是修改後的代碼。 寫入保存寫入套接字的整數個數。

FileInputStream fis = new FileInputStream(fil); 
BufferedInputStream in = new BufferedInputStream(fis); 
BufferedOutputStream out = new BufferedOutputStream(skt.getOutputStream()); 

//Write the file to the server socket   
int i; 
int written = 0; 

while ((i = in.read()) != -1) { 

    out.write(i);    
    publishProgress(++written); 
    System.out.println(i); 
} 
0

要做到這一點,你需要做的幾件事情之一:

  1. 使用Flash上​​傳諸如swfupload(見http://demo.swfupload.org/Documentation/),因爲這些通常提供訪問上傳這種進步。
  2. 提供自己的背溝道:執行的形式使用Ajax提交,然後同時提交表單時您運行命中服務器上的URL與一些對應於上傳類型的關鍵一個JavaScript計時器。在服務器上的網址查找多少文件已被上傳,並返回數量和傳遞,通過你的uploadProgress方法。
0

javax.swing.ProgressMonitorInputStream中