在android中将多个文件上载到服务器时的进度条
我将文件(视频和照片)从android上传到php服务器 我使用这个代码:在android中将多个文件上载到服务器时的进度条,android,file-upload,asynchronous,progress-bar,Android,File Upload,Asynchronous,Progress Bar,我将文件(视频和照片)从android上传到php服务器 我使用这个代码: @SuppressWarnings("deprecation") protected String doInBackground(String... args) { // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); Utils.d(Config.REST
@SuppressWarnings("deprecation")
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
Utils.d(Config.REST_SERVER + url_connect);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.REST_SERVER+url_connect);
try {
@SuppressWarnings("deprecation")
MultipartEntity entity = new MultipartEntity();
entity.addPart("userId", new StringBody(this.userId));
entity.addPart("orderId", new StringBody(this.orderId));
Utils.d("size totale avant : "+this.files.size());
int i = 0;
for(File f:this.files){
entity.addPart("nameFile", new StringBody(f.getName()));
i++;
entity.addPart("files[]", (ContentBody) new FileBody(f));
}
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
Log.d("Create Response", json);
jObj = new JSONObject(json);
Log.d("Create Response", jObj.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return null;
}
@SuppressWarnings(“弃用”)
受保护的字符串doInBackground(字符串…args){
//建筑参数
List params=new ArrayList();
Utils.d(Config.REST\u SERVER+url\u connect);
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost-HttpPost=newhttppost(Config.REST\u SERVER+url\u connect);
试一试{
@抑制警告(“弃用”)
多方实体=新多方实体();
entity.addPart(“userId”,新的StringBody(this.userId));
entity.addPart(“orderId”,新的StringBody(this.orderId));
Utils.d(“size totale avant:+this.files.size());
int i=0;
for(文件f:this.files){
entity.addPart(“名称文件”,新的StringBody(f.getName());
i++;
addPart(“files[]”,(ContentBody)newfilebody(f));
}
httppost.setEntity(实体);
HttpResponse response=httpclient.execute(httppost);
HttpEntity HttpEntity=response.getEntity();
is=httpEntity.getContent();
试一试{
BufferedReader reader=新的BufferedReader(新的InputStreamReader(
is,“iso-8859-1”),8);
StringBuilder sb=新的StringBuilder();
字符串行=null;
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
is.close();
json=sb.toString();
}捕获(例外e){
Log.e(“缓冲区错误”,“错误转换结果”+e.toString());
}
//尝试将字符串解析为JSON对象
试一试{
Log.d(“创建响应”,json);
jObj=新的JSONObject(json);
Log.d(“创建响应”,jObj.toString());
}捕获(JSONException e){
Log.e(“JSON解析器”,“错误解析数据”+e.toString());
}
}捕获(客户端协议例外e){
}捕获(IOE异常){
}
返回null;
}
我想制作尽可能多的progressbar文件,这些progressbar将根据发送到服务器的Bytte的百分比改变状态
有什么办法吗
提前谢谢你像这样试试
参考开源项目,在上传时显示水平进度条。它将在ProgressBar
中显示上传的%字节
public class MyMultipartEntity extends MultipartEntity{
private final ProgressListener listener;
public MyMultipartEntity(final ProgressListener listener)
{
super();
this.listener = listener;
}
public MyMultipartEntity(final HttpMultipartMode mode, final ProgressListener listener)
{
super(mode);
this.listener = listener;
}
public MyMultipartEntity(HttpMultipartMode mode, final String boundary, final Charset charset, final ProgressListener listener)
{
super(mode, boundary, charset);
this.listener = listener;
}
@Override
public void writeTo(final OutputStream outstream) throws IOException
{
super.writeTo(new CountingOutputStream(outstream, this.listener));
}
public static interface ProgressListener
{
void transferred(long num);
}
public static class CountingOutputStream extends FilterOutputStream
{
private final ProgressListener listener;
private long transferred;
public CountingOutputStream(final OutputStream out, final ProgressListener listener)
{
super(out);
this.listener = listener;
this.transferred = 0;
}
public void write(byte[] b, int off, int len) throws IOException
{
out.write(b, off, len);
this.transferred += len;
this.listener.transferred(this.transferred);
}
public void write(int b) throws IOException
{
out.write(b);
this.transferred++;
this.listener.transferred(this.transferred);
}
}
}
如何在AsyncTask中使用它来显示ProgressBar
public class HttpUpload extends AsyncTask<Void, Integer, Void> {
private Context context;
private String imgPath;
private HttpClient client;
private ProgressDialog pd;
private long totalSize;
private static final String url = "YOUR_URL";
public HttpUpload(Context context, String imgPath) {
super();
this.context = context;
this.imgPath = imgPath;
}
@Override
protected void onPreExecute() {
//Set timeout parameters
int timeout = 10000;
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeout);
HttpConnectionParams.setSoTimeout(httpParameters, timeout);
//We'll use the DefaultHttpClient
client = new DefaultHttpClient(httpParameters);
pd = new ProgressDialog(context);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMessage("Uploading Picture/Video...");
pd.setCancelable(false);
pd.show();
}
@Override
protected Void doInBackground(Void... params) {
try {
File file = new File(imgPath);
//Create the POST object
HttpPost post = new HttpPost(url);
//Create the multipart entity object and add a progress listener
//this is a our extended class so we can know the bytes that have been transfered
MultipartEntity entity = new MyMultipartEntity(new ProgressListener()
{
@Override
public void transferred(long num)
{
//Call the onProgressUpdate method with the percent completed
publishProgress((int) ((num / (float) totalSize) * 100));
Log.d("DEBUG", num + " - " + totalSize);
}
});
//Add the file to the content's body
ContentBody cbFile = new FileBody( file, "image/jpeg" );
entity.addPart("source", cbFile);
//After adding everything we get the content's lenght
totalSize = entity.getContentLength();
//We add the entity to the post request
post.setEntity(entity);
//Execute post request
HttpResponse response = client.execute( post );
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode == HttpStatus.SC_OK){
//If everything goes ok, we can get the response
String fullRes = EntityUtils.toString(response.getEntity());
Log.d("DEBUG", fullRes);
} else {
Log.d("DEBUG", "HTTP Fail, Response Code: " + statusCode);
}
} catch (ClientProtocolException e) {
// Any error related to the Http Protocol (e.g. malformed url)
e.printStackTrace();
} catch (IOException e) {
// Any IO error (e.g. File not found)
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Integer... progress) {
//Set the pertange done in the progress dialog
pd.setProgress((int) (progress[0]));
}
@Override
protected void onPostExecute(Void result) {
//Dismiss progress dialog
pd.dismiss();
}
}
公共类HttpUpload扩展异步任务{
私人语境;
私有字符串imgPath;
私有HttpClient;
私营部门;
私人长期总规模;
私有静态最终字符串url=“您的url”;
公共HttpUpload(上下文,字符串imgPath){
超级();
this.context=上下文;
this.imgPath=imgPath;
}
@凌驾
受保护的void onPreExecute(){
//设置超时参数
int超时=10000;
HttpParams httpParameters=新的BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,超时);
HttpConnectionParams.setSoTimeout(httpParameters,超时);
//我们将使用DefaultHttpClient
client=新的DefaultHttpClient(httpParameters);
pd=新进度对话框(上下文);
pd.setProgressStyle(ProgressDialog.STYLE_水平);
pd.setMessage(“上传图片/视频…”);
pd.可设置可取消(假);
pd.show();
}
@凌驾
受保护的Void doInBackground(Void…参数){
试一试{
File File=新文件(imgPath);
//创建POST对象
HttpPost=新的HttpPost(url);
//创建多部分实体对象并添加进度侦听器
//这是一个扩展类,因此我们可以知道已传输的字节
MultipartEntity=new MyMultipartEntity(new ProgressListener())
{
@凌驾
已转移的公共无效(长数值)
{
//使用完成百分比调用onProgressUpdate方法
出版进度((int)((num/(float)totalSize)*100);
Log.d(“调试”,num+“-”+总大小);
}
});
//将文件添加到内容的正文中
ContentBody cbFile=新文件体(文件“image/jpeg”);
entity.addPart(“源”,cbFile);
//添加所有内容后,我们得到内容的长度
totalSize=entity.getContentLength();
//我们将实体添加到post请求中
后设实体(实体);
//执行post请求
HttpResponse response=client.execute(post);
int statusCode=response.getStatusLine().getStatusCode();
if(statusCode==HttpStatus.SC\u OK){
//如果一切顺利,我们可以得到答复
字符串fullRes=EntityUtils.toString(response.getEntity());
Log.d(“调试”,fullRes);
}否则{
Log.d(“调试”,“HTTP失败,响应代码:“+statusCode”);
}
}捕获(客户端协议例外e){
//与Http协议相关的任何错误(例如ma