如何在android中实现文件上传进度条

时间:2011-08-03 09:38:56

标签: android

我在android中通过org.apache.http.client.HttpClient上传文件,我需要实现进度条。是否有可能从以下方面获取进展:?

HttpPost httppost = new HttpPost("some path");
HttpClient httpclient = new DefaultHttpClient();
try {
File file = new File("file path");
InputStream in = new BufferedInputStream(new FileInputStream(file));
byte[] bArray = new byte[(int) file.length()];
in.read(bArray);
String entity = Base64.encodeToString(bArray, Base64.DEFAULT);
httppost.setEntity(new StringEntity(entity));
HttpResponse response = httpclient.execute(httppost);
}

如果没有,请显示另一种方式。感谢

2 个答案:

答案 0 :(得分:22)

您要做的是创建一个可以为您处理此问题的AsyncTask,覆盖onProgressUpdate方法。

这是我使用HttpURLConnection在另一个应用中测试的内容的精简版本。可能会有一些小的冗余,我认为HttpURLConnection可能通常不赞成,但这应该有效。只需通过调用TheActivity在您正在使用的任何Activity类中使用此类(在此示例中,我将其称为new FileUploadTask().execute())。当然,您可能需要调整它以满足您的应用程序的需求。

private class FileUploadTask extends AsyncTask<Object, Integer, Void> {

    private ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        dialog = new ProgressDialog(TheActivity.this);
        dialog.setMessage("Uploading...");
        dialog.setIndeterminate(false);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setProgress(0);
        dialog.show();
    }

    @Override
    protected Void doInBackground(Object... arg0) {
        try {
            File file = new File("file path");
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] bytes = new byte[(int) file.length()];
            fileInputStream.read(bytes);
            fileInputStream.close();

            URL url = new URL("some path");
            HttpURLConnection connection = 
                    (HttpURLConnection) url.openConnection();
            OutputStream outputStream = connection.getOutputStream();

            int bufferLength = 1024;
            for (int i = 0; i < bytes.length; i += bufferLength) {
                int progress = (int)((i / (float) bytes.length) * 100);
                publishProgress(progress);
                if (bytes.length - i >= bufferLength) {
                    outputStream.write(bytes, i, bufferLength);
                } else {
                    outputStream.write(bytes, i, bytes.length - i);
                }
            }
            publishProgress(100);

            outputStream.close();
            outputStream.flush();

            InputStream inputStream = connection.getInputStream();
            // read the response
            inputStream.close();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        dialog.setProgress(progress[0]);
    }

    @Override
    protected void onPostExecute(Void result) {
        try {
            dialog.dismiss();
        } catch(Exception e) {
        }

    }

}

答案 1 :(得分:4)

我不认为HttpURLConnection只是这样做,正如@Basbous指出的那样,实际数据是缓冲的,直到调用outputStream.flush()。根据android issue 3164,它现在已在post-froyo平台(android 2.2,sdk version 8)中修复,你需要使用 - java.net.HttpURLConnection.setFixedLengthStreamingMode来解决缓冲行为。