簡體   English   中英

如何監控文件上傳進度?

[英]How to monitor file upload progress?

我需要將文件上傳到服務器並監控它的進度。 我需要通知每次發送多少字節。

例如,在下載的情況下,我有:

HttpURLConnection  connection = (HttpURLConnection) m_url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
while ((currentBytes  = stream.read(byteBuffer)) > 0) {                    
    totalBytes+=currentBytes;
    //calculate something...
}

現在我需要為上傳做同樣的事情。 但如果使用

OutputStreamWriter stream = new OutputStreamWriter(connection.getOutputStream());
stream.write(str);
stream.flush();

比我無法收到任何進度通知,關於發送了多少字節(它看起來像自動操作)。

有什么建議么?

謝謝

只需設置分塊傳輸模式並監控您自己對 output stream 的寫入。

如果不使用分塊或定長傳輸模式,則在寫入網絡之前,您的寫入全部寫入到 ByteArrayOutputStream,這樣 Java 就可以正確設置 Content-Length header。 這就是讓您認為它是非阻塞的原因。 它不是。

我用過 ChannelSocket object。 這個 object 允許在訪問服務器時進行阻塞讀寫。 所以我使用這個套接字模擬了 HTTP 並且每個寫請求都被阻塞,直到它完成。 這樣我就可以跟蹤寫事務的實際進度。

我在類似情況下所做的是創建一個FilterOutputStream的子類,它覆蓋 write(...) 方法,然后可以通知您的代碼任何寫入的字節。

If you want to count the bytes you're uploading, write the objects as byte arrays to the output stream itself, like you are doing with the input stream.

這將類似於您的下載工作方式。

OutputStream stream = connection.getOutputStream();
for(byte b: str.getBytes()) {                    
    totalBytes+=1;
    stream.write(b);
    if(totalBytes%50 == 0)
        stream.flush(); //bytes will be sent in chunks of 50
    //calculate something...
}
stream.flush();

類似的東西。

另一種方法是輪詢服務器,詢問上傳了多少數據。 也許使用 id 或其他東西。

POST -> /上傳文件

  • ID
  • 文件

POST -> /queryuploadstate(返回部分大小)

  • ID

當然它需要連接 servlets 並且不允許集群...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM