2012-07-12 15 views
6

का उपयोग कर एंड्रॉइड से रेल सर्वर पर छवि अपलोड करने में समस्या मैं एंड्रॉइड से अपने रेल सर्वर पर छवियों को अपलोड करने की कोशिश कर रहा हूं। मेरे सभी अन्य डेटा अपलोड, लेकिन मुझे "त्रुटि अमान्य शरीर आकार" त्रुटि मिलती है। इसे छवि के साथ करना है। नीचे मेरा कोड है। मदद?!पेपरक्लिप

public void post(String url) { 
      HttpClient httpClient = new DefaultHttpClient(); 
      HttpContext localContext = new BasicHttpContext(); 
      HttpPost httpPost = new HttpPost(url); 
      httpPost.addHeader("content_type","image/jpeg"); 
      try { 
       MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 
       entity.addPart("picture_file_name", new StringBody("damage.jpg")); 
       File file = new File((imageUri.toString())); 
       entity.addPart("picture", new FileBody(file, "image/jpeg")); 
       httpPost.setEntity(entity);   
       HttpResponse response = httpClient.execute(httpPost, localContext); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 

मैंने ब्राउज़र संगत पैरामीटर को हटाने का प्रयास किया है, लेकिन इससे मदद नहीं मिलती है। मेरी छवि को छवि यूआरआई नामक यूआरआई के रूप में संग्रहीत किया जा रहा है। मैं पेपरक्लिप मणि का उपयोग कर रहा हूँ।

धन्यवाद!

उत्तर

6

इस प्रकार मैंने हल किया।

MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 
    for (NameValuePair nameValuePair : nameValuePairs) { 
     if (nameValuePair.getName().equalsIgnoreCase("picture")) { 
       File imgFile = new File(nameValuePair.getValue()); 
       FileBody fileBody = new FileBody(imgFile, "image/jpeg"); 
       multipartEntity.addPart("post[picture]", fileBody); 
     } else { 
       multipartEntity.addPart("post[" + nameValuePair.getName() + "]", new StringBody(nameValuePair.getValue())); 
     }     
    } 
httpPost.setEntity(multipartEntity); 
HttpResponse response = httpClient.execute(httpPost, httpContext); 

यह इस तरह की एक पोस्ट का उत्पादन करेगा:

{"post"=>{"description"=>"fhgg", "picture"=>#<ActionDispatch::Http::UploadedFile:0x00000004a6de08 @original_filename="IMG_20121211_174721.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"post[picture]\"; filename=\"IMG_20121211_174721.jpg\"\r\nContent-Type: image/jpeg\r\nContent-Transfer-Encoding: binary\r\n", @tempfile=#<File:/tmp/RackMultipart20121211-7101-3vq9wh>>}} 

रेल आवेदन अपने मॉडल जिम्मेदार बताते हैं, एक ही नाम आप अपने अनुरोध में उपयोग होना आवश्यक है ताकि मेरे मामले में में

class Post < ActiveRecord::Base 
    attr_accessible :description, :user_id, :picture 

    has_attached_file :picture # Paperclip stuff 
... 
end 

मैंने रेल आवेदन से सीएसआरएफ टोकन भी अक्षम कर दिया है।

संबंधित मुद्दे