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();


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;

    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(
        reqEntity.addPart("file", fileBody);

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

        if (resEntity != null) {

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

        return null;


No comments:

Post a Comment