HOW TO - Uploading image from android to rails server - multipart
I'm developing an Android app and I'm working on photo uploading to my rails server.
If I upload ad image from browser, server gives me this (I'm using paperclip gem to upload):
COMMIT CODE
[...] , "immagine"=>#
<ActionDispatch::Http::UploadedFile:0x103026dc8 @headers="Content-Disposition: form-data; name=\"segnalazione[immagine]\";
filename=\"24e14f4a46269f89ace12297b9ed4060aa3b44f5.jpeg\"\r\nContent-Type: image/jpeg\r\n", @content_type="image/jpeg", @tempfile=#<File:/var/folders/Ht/HtQoVYewE-i8RHpa2OY38U+++TI/-Tmp-/RackMultipart20110711-31693-p0wpzx-0>,
@original_filename="24e14f4a46269f89ace12297b9ed4060aa3b44f5.jpeg">,
[...]
My question is: how can I use multipart to upload correctly? On android, working with json objects I used:
HttpPost post = new HttpPost("http://10.0.2.2:3000/segnalaziones?format=json");
JSONObject eventObj = new JSONObject();
JSONObject holder = new JSONObject();
try {
// Genero l'oggetto JSON
eventObj.put("categoria1", c1);
eventObj.put("categoria2", c2);
eventObj.put("categoria3", c3);
eventObj.put("descrizione", descr);
eventObj.put("dove", coord);
eventObj.put("mood", mood);
eventObj.put("via", via);
//eventObj.put("android", android);
holder.put("commit", "Spedisci");
holder.put("segnalazione", eventObj);
Log.e("Event JSON", "Event JSON = "+ holder.toString());
StringEntity richiesta = new StringEntity(holder.toString());
post.setEntity(richiesta);
post.setHeader("Content-Type","application/json");
UPDATE
I've tried
HttpPost post = new HttpPost("http://10.0.2.2:3000/segnalaziones");
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.B开发者_开发百科ROWSER_COMPATIBLE);
multipartEntity.addPart("commit", new StringBody("Spedisci"));
multipartEntity.addPart("segnalazione[immagine]", new FileBody(photo));
post.setEntity(multipartEntity);
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
resEntity.consumeContent();
}
.. but in this case server receives well but doesn't "insert into".
Please look at the screens ... This screen is the post from browser ... all goes well
http://imageshack.us/photo/my-images/219/brozk.png/
This from android ... no "insert into" ... WHY??
http://imageshack.us/photo/my-images/13/andvv.png/
NOTE THAT if I send the same post without adding an image ... "INSERT INTO" works
here is a nice article link. This helped me to upload image from android device to server. I hope it will also help to you.
精彩评论