如何在android中实现file upload进度条

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

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

如果没有,请展示另一种方法。 谢谢

Solutions Collecting From Web of "如何在android中实现file upload进度条"

你想要做的是创build一个AsyncTask ,可以为你处理这个,覆盖onProgressUpdate方法。

这里是我使用HttpURLConnection在另一个应用程序中testing的一个精简版本。 可能会有一些小的冗余,我认为HttpURLConnection可能普遍皱起了眉头,但这应该工作。 只需要调用new FileUploadTask().execute() ,就可以在你使用的任何Activity类(在这个例子中,我称之为TheActivity )中使用这个类。 当然,你可能需要调整这个来适应你的应用程序的需求。

 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) { } } } 

我不认为HttpURLConnection简单地做了这个伎俩,因为@Basbous指出,实际的数据被缓冲,直到outputStream.flush()被调用。 根据android 问题3164 ,它现在修复后的froyo平台(android 2.2,sdk版本8),您需要使用 – java.net.HttpURLConnection.setFixedLengthStreamingMode来解决缓冲区行为。