Pages

Wednesday, 18 December 2013

Android upload multiple files to server using http


Add following file to your project. there is one demo function which upload file like (audio/video song) to server. you can pass other params also. like song name , artist etc. set your api's url to "AudioVideoBaseURL" variable


public class Soap {
 
 

 public static String AudioVideoBaseURL = "http://abcd.com";

 

 public static String getSoapResponseForVideoAudio(String postFixOfUrl,
   List nameValuePairs,
   List filenameValuePairs) {
  String xmlString = null;
  HttpClient httpClient = new DefaultHttpClient();
  HttpContext localContext = new BasicHttpContext();
  HttpPost httpPost = new HttpPost(AudioVideoBaseURL + postFixOfUrl);

  try {
   MultipartEntity entity = new MultipartEntity();

   for (int index = 0; index < filenameValuePairs.size(); index++) {
    File myFile = new File(filenameValuePairs.get(index).getValue());
    FileBody fileBody = new FileBody(myFile);
    entity.addPart(filenameValuePairs.get(index).getName(),
      fileBody);
   }

   for (int index = 0; index < nameValuePairs.size(); index++) {

    entity.addPart(nameValuePairs.get(index).getName(),
      new StringBody(nameValuePairs.get(index).getValue(),
        Charset.forName("UTF-8")));

   }

   httpPost.setEntity(entity);

   HttpResponse response = httpClient.execute(httpPost, localContext);
   HttpEntity r_entity = response.getEntity();
   xmlString = EntityUtils.toString(r_entity);

  } catch (IOException e) {
   e.printStackTrace();
  }
  return xmlString.toString();
 }


 public static String apiUploadSong(int userId, int songId,
   String songTitle, String songArtist, String isVideo, String fileData)
   throws ClientProtocolException, IOException {

  ArrayList alNameValuePairsFile = new ArrayList();
  NameValuePair nameValuePairsFile = new BasicNameValuePair("fileData",
    fileData);
  alNameValuePairsFile.add(nameValuePairsFile);

  ArrayList alNameValuePairs = new ArrayList();

  NameValuePair nameValuePairs = new BasicNameValuePair("userId", ""
    + userId);
  alNameValuePairs.add(nameValuePairs);
  nameValuePairs = new BasicNameValuePair("songId", ""+songId);
  alNameValuePairs.add(nameValuePairs);
  nameValuePairs = new BasicNameValuePair("songTitle", songTitle);
  alNameValuePairs.add(nameValuePairs);
  nameValuePairs = new BasicNameValuePair("songArtist", songArtist);
  alNameValuePairs.add(nameValuePairs);
  nameValuePairs = new BasicNameValuePair("isVideo", isVideo);
  alNameValuePairs.add(nameValuePairs);

  String result = Soap.getSoapResponseForVideoAudio(
    "?action=save_video_audio", alNameValuePairs,
    alNameValuePairsFile);
  Log.e("SOAP", "save_video_audio : " + result);

  return result;
 }
}


now just add following jar file to your libs folder
apache-mime4j-0.6.jar
httpmime-4.0.1.jar