How to upload file in android

Here is a full source code for how to upload file in android app
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;

public class t extends Activity {

        String url;

@Override
protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 url = "Your URL here";
 new sendFile().execute(url);

}
private class sendFile extends AsyncTask {
 @Override
 protected String doInBackground(String... params) {
 String uri = params[0];
 try {
  String address;
  MultipartEntity entity;
  File f;
  FileBody fb;
  entity = new MultipartEntity(
    HttpMultipartMode.BROWSER_COMPATIBLE);
  address = Environment.getExternalStorageDirectory()
   + "/temp.dat";
  f = new File(address);
  fb = new FileBody(f, "application/octect-stream");
  entity.addPart("file", fb);
  HttpClient httpclient = new DefaultHttpClient();
  HttpPost httppost = new HttpPost(uri);
  httppost.setEntity(entity);
  HttpResponse response = httpclient.execute(httppost);
  BufferedReader bufferedReader = new BufferedReader(
    new InputStreamReader(
     response.getEntity().getContent()));
  StringBuffer stringBuffer = new StringBuffer("");
  String line = "";
  String LineSeparator = System.getProperty("line.separator");
  while ((line = bufferedReader.readLine()) != null) {
   stringBuffer.append(line + LineSeparator);
  }
  bufferedReader.close();
  return stringBuffer.toString();
   catch (ClientProtocolException e) {
  return e.toString();
  } catch (IOException e) {
  return e.toString();
  }
 }

 protected void onPostExecute(String result) {
  Toast.makeText(getApplicationContext(), 
   result, Toast.LENGTH_LONG).show();
 }
}

}


Ads :
Electronics, Cars, Fashion, Collectibles, Coupons and More Online Shopping | eBay
www.ebay.com | www.ebay.com.my

No comments:

Post a Comment