使用multipart上传图像时如何在客户端获取进程

时间:2013-07-16 02:42:17

标签: java android apache file-upload

我正在开发一个需要使用Multipart上传图片的项目。 这是我的代码:

public void doUploadGIF(File image) {

        try {
            long start = System.currentTimeMillis();
            HttpPost httppost = new HttpPost(
                    "myurl");
            MultipartEntity multipartEntity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);

            multipartEntity.addPart("gif", new FileBody(image));
            httppost.setEntity(multipartEntity);

            mHttpClient.execute(httppost, new PhotoUploadResponseHandler());

            long end = System.currentTimeMillis();
            System.out.println("Time for uploading:"
                    + String.valueOf(end - start));
        } catch (Exception e) {
            Log.e("Upload", "Error while uploading");
        }
    }

private class PhotoUploadResponseHandler implements ResponseHandler<Object> {

        @Override
        public Object handleResponse(HttpResponse response)
                throws ClientProtocolException, IOException {

            HttpEntity r_entity = response.getEntity();
            String responseString = EntityUtils.toString(r_entity); 
            Log.d("UPLOAD", responseString);

            return null;
        }

    }

现在在客户端(Android)我让用户知道上传过程(百分比)。 我怎样才能做到这一点? 感谢您的关注 !

1 个答案:

答案 0 :(得分:0)

在我的情况下,我使用KB的文件大小,并设置进度条的限制,文件大小以KB为单位。并用于更新我使用的进度条:

int bufferLength = 1024;

File file = new File(ImgURI);
mFileLen =  file.length();

int maxBufferSize = 1*1024*1024;

bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);

for (int i = 0; i < bufferSize; i +=bufferLength) {
    progress = i/1024;
    progressBar1.setMax(kbfilesize);
    publishProgress(progress);
}