Tuesday, October 29, 2013

Upload Files to server from Sdcard in android

 Need to Add  Httpmime.jar to your Build path
 Call AsyncTask:
 new UploadFileService ("upload Url",
            file name, file path).execute();

AsyncTask:

import java.io.File;
import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
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 org.apache.http.util.EntityUtils;

import android.os.AsyncTask;

public class UploadFileService extends AsyncTask<Void, Void, Void> {
    private String posturl;
    private String fileName;
    private String filePath;

    public UploadFileService (String posturl, String filename,
            String filePath) {
        this.fileName = filename;
        this.posturl = posturl;
        this.filePath = filePath;
    }

    @Override
    protected Void doInBackground(Void... params) {
        // new HttpClient
        HttpClient httpClient = new DefaultHttpClient();

        // post header
        HttpPost httpPost = new HttpPost(posturl);

        File file = new File(filePath + "/" + fileName);

        FileBody fileBody = new FileBody(file);

        MultipartEntity reqEntity = new MultipartEntity(
                HttpMultipartMode.BROWSER_COMPATIBLE);
        reqEntity.addPart("file", fileBody);
        httpPost.setEntity(reqEntity);

        // execute HTTP post request
        HttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpEntity resEntity = response.getEntity();

        if (resEntity != null) {

            try {
                String responseStr = EntityUtils.toString(resEntity).trim();
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            // you can add an if statement here and do other actions based
            // on response
        }

        return null;
    }

}

No comments:

Post a Comment