Android: Uploading a photo in Cloudinary with progress callback in HttpURLConnection

后端 未结 2 1425
Happy的楠姐
Happy的楠姐 2021-01-12 03:51

I\'m trying to modify the open source library of cloudinary so that I can listen to the progress of the upload of my photo. The library class contains a MultipartUtility jav

2条回答
  •  北荒
    北荒 (楼主)
    2021-01-12 04:01

    This is a shot in the dark because I have not tested on an Android environment, however I would recommend trying the following.

    Instead of using a fixed length use setChunkedStreamingMode

    //httpConn.setFixedLengthStreamingMode(filesize);
    httpConn.setChunkedStreamingMode(4096); // or whatever size you see fit
    

    doing this should trigger part of the request to get sent every time you send in 4096 bytes of data and essentially flushing out the internal buffer.


    You could also try manually flushing the buffer after each write, this could slow down the file upload especially if you flush to often however it would likely fix your problem. You might end up playing with buffer sizes to find a sweet spot.

    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
        progress += bytesRead;
        /* int percentage = ((progress / filesize.intValue()) * 100);*/
        if (uploadingCallback != null) {
            uploadingCallback.uploadListener(progress);
        }
        // trigger the stream to write its data
        outputStream.flush();
     }
    

    With either of these changes you would likely want to let the user choose to set their own buffer size instead of passing in the total file size. EG change your constructor to the following:

    MultipartUtility(String requestURL, String charset, 
                     String boundary, Map headers, int chunkSize)
    

提交回复
热议问题