Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I upload Images AND text using UrlEncodedFormEntity for multi part?

Images often requires special HTTP headers like:

Content-disposition: attachment; filename="file2.jpeg"
Content-type: image/jpeg
Content-Transfer-Encoding: binary

I'm building my POST using:

List<NameValuePair> formparams = new ArrayList<NameValuePair>();
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams);

urlEncodedFormEntity allows setContentType, but I don't see how I can MIX both images and text ??

like image 749
hunterp Avatar asked Jul 22 '11 23:07

hunterp


1 Answers

try {
   File file = new File(Environment.getExternalStorageDirectory(),"FMS_photo.jpg");

   HttpClient client = new DefaultHttpClient();  
   HttpPost post = new HttpPost("http://homepage.com/path");  
   FileBody bin = new FileBody(file);  


   Charset chars = Charset.forName("UTF-8");

   MultipartEntity reqEntity = new MultipartEntity();  
   reqEntity.addPart("problem[photos_attributes][0][image]", bin);  
   reqEntity.addPart("myString", new StringBody("17", chars));

   post.setEntity(reqEntity); 
   HttpResponse response = client.execute(post);  

   HttpEntity resEntity = response.getEntity();  
   if (resEntity != null) {    
     resEntity.consumeContent();  
  }

   return true;

  } catch (Exception ex) {

    globalStatus = UPLOAD_ERROR;
    serverResponse = "";
    return false;
  } finally {

 }

in this the problem attribute will carry the image and myString carry the string...

like image 169
Dinash Avatar answered Oct 20 '22 16:10

Dinash