如何知道在 android 中上传到服务器的文件百分比

How to know how much percentage file uploaded to server in android

我正在使用此代码将文件从我的 android 上传到服务器,但我不知道我的文件上传了多少(例如 30MB 来自 100MB)! 有什么办法吗?

String url = "http://yourserver";
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),
    "yourfile");
try {
HttpClient httpclient = new DefaultHttpClient();

HttpPost httppost = new HttpPost(url);

InputStreamEntity reqEntity = new InputStreamEntity(
        new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
//Do something with response...

} catch (Exception e) {
// show error
}

为此,您使用了 AsyncTask 并使用 publishProgress() 方法设置了 ProgressDialog 百分比。有关详细信息,请访问此 link.

你好,要使用互联网,你必须使用新线程,但在线程中我们无法访问主线程,因此创建一个新的 runonuithread 并从中更改进度

new Thread(new Runnable() {
        @Override
        public void run() {
            /*
            upload codes goes here
             */

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //set value of progressbar here
                }
            });
        }
    }).start();