Reputation: 2174
I upload files (videos and photos) from android to php server and I use this code :
@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;
}
and I want to make as many progressbar as files and those progressbar will change states according to percent of byttes sent to the server
is there any way to do that
thank you in advance
Upvotes: 1
Views: 2198
Reputation: 8939
Try like this.
For reference GitHub open source project to show Horizontal ProgressBar
while uploading. It will show % of byte uploading in 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);
}
}
}
How to use it in AsyncTask to show 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();
}
}
Hope This will help you.
Upvotes: 2