gpt4 book ai didi

android - android中文件上传进度条的实现方法

转载 作者:可可西里 更新时间:2023-11-01 18:57:25 31 4
gpt4 key购买 nike

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

如果没有,请提供替代方法。谢谢

最佳答案

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

这是我在另一个应用程序中使用 HttpURLConnection 测试的精简版。可能会有一些小的冗余,我认为 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) {
}

}

}

关于android - android中文件上传进度条的实现方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6924447/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com