How to monitor file upload progress?

老子叫甜甜 提交于 2019-12-22 10:49:49

问题


I need to upload a file to server and monitor it's progress. i need to get a notification how many bytes are sent each time.

For example in case of download i have:

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

Now i need to do the same for upload. but if use

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

than i can't get any progres notification, about how many bytes are sent (it looks like automic action).

Any suggestions?

Thanks


回答1:


Just set chunked transfer mode and monitor your own writes to the output stream.

If you don't use chunked or fixed-length transfer mode, your writes are all written to a ByteArrayOutputStream before being written to the network, so that Java can set the Content-Length header correctly. This is what made you think it is non-blocking. It isn't.




回答2:


I have used ChannelSocket object. This object allows to do blocking read and write when accessing the server. So i emulated HTTP using this socket and each write request was blocked untill it was done. This way i could follow the actual progress of write transaction.




回答3:


What I have done in similar situations is create a subclass of FilterOutputStream which overrides the write(...) methods and can then notify your code of any written bytes.




回答4:


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.




回答5:


It would be similar to the way your download works.

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();

Something like that.




回答6:


A different approach is polling the server asking how much of the data is uploaded. Maybe using an id or something.

POST -> /uploadfile

  • id
  • file

POST -> /queryuploadstate (Returns the partial size)

  • id

Of course it needs the servlets to be connected and doesn't allow clustering...



来源:https://stackoverflow.com/questions/6294661/how-to-monitor-file-upload-progress

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!