I'm trying to upload images to my rails server from Android. All my other data uploads, but I get a "Error invalid body size" error. It has to do with the image. Below is my code. Help?!
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();
}
}
I've tried removing the browser compatible parameter, but it doesn't help. my image is being stored as an URI called imageUri. I'm using paperclip gem.
thanks!
This is how I solved.
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);
This will produce a POST like this:
{"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>>}}
In the rails application your model attributes must have the same name you use in your request
, so in my case
class Post < ActiveRecord::Base
attr_accessible :description, :user_id, :picture
has_attached_file :picture # Paperclip stuff
...
end
I have also disabled the CSRF token from the rails application.
Related
I have struggled for quite some time to upload photo images from android to python appengine
This is what I have tried, in Android:
void apachePost() throws Exception {
File image = new File("/sdcard/image.jpg");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://clockinapple.appspot.com/upload");
try {
MultipartEntity entity = new MultipartEntity();
entity.addPart("type", new StringBody("photo"));
entity.addPart("data", new FileBody(image));
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
Log.v(Constants.DATA, "received http response " + response);
} catch (ClientProtocolException e){
}
}
In appengine:
class UserPhoto(db.Model):
user = db.StringProperty()
blob_key = blobstore.BlobReferenceProperty()
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
upload = self.get_uploads()[0]
user_photo = UserPhoto(user="test", blob_key=upload.key())
db.put(user_photo)
return user_photo.key()
My logged server error is "Apache-HttpClient/UNAVAILABLE (java 1.4)"
I assume the headers are incorrect - I have tried many variations
Some of the links are have tried:
Ika Lan's snippet
tacticalnuclearstrike blog
I would really appreciate any help, I don't seem to be asking the right questions atm
This is what I have that works (Changed to a HttpGet), the Android code:
void apachePost(String url, String filename) throws Exception {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse urlResponse = httpClient.execute(httpGet);
String result = EntityUtils.toString(urlResponse.getEntity());
Uri fileUri = Uri.parse(filename); // Gets the Uri of the file in the sdcard
File file = new File(new URI(fileUri.toString())); // Extracts the file from the Uri
FileBody fileBody = new FileBody(file, "multipart/form-data");
StringBody stringBody = new StringBody("Arghhh");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("file", fileBody);
entity.addPart("string", stringBody);
HttpPost httpPost = new HttpPost(result);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
response.getStatusLine();
Log.v(Constants.DATA, "received http response " + response);
Log.v(Constants.DATA, "received http entity " + entity);
}
The Appengine Code:
class GetBlobstoreUrl(BaseHandler):
def get(self):
upload_url = blobstore.create_upload_url('/upload/')
logging.debug(upload_url)
self.response.out.write(upload_url)
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
upload_files = self.get_uploads('file')
text_files = self.get_uploads('string')
blob_info = upload_files[0]
user_info = "text_files"
photo = clockin.UserPhoto(blob_key=blob_info.key(), user=user_info)
photo.put()
One thing that eludes me is what happened to the "entity.addPart("string", stringBody);"
it doesnt seem part of get_uploads in the blobstore object
What I want I want to send a video from my SDcard to a server. I also want to send some parameters/value with it.
I have tried I have tried the following code:
public String SendToServer(String aUrl,File aFile)
{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(aUrl);
try
{
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("file", new FileBody(aFile));
entity.addPart("video[title]", new StringBody("testVideo"));
entity.addPart("video[type]", new StringBody("1"));
httpPost.setEntity(entity);
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, Globals.sessionCookie);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity resEntity = response.getEntity();
String Response = "";
if (response != null)
{
Response = EntityUtils.toString(resEntity);
}
return Response;
}
catch (IOException e)
{
e.printStackTrace();
}
return "Exception";
}
What is the problem When I run this code, I get stuck at this line
HttpResponse response = httpClient.execute(httpPost, localContext);
I get no exception, no response nothing at all. Can anyone please guide me, what is the problem in here?
The above code in my question was perfect, but I had the network problem. My device was connected to a hotspot(Connectify Software). When I connected to the original network, this code worked perfect.
I recommend you people to never trust a hotspot for this kind of functionality.
try using this way if want to send as content or esle I will upload the project by tonight
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(filePath), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
I have a web service which requires me to send file data to HTTP url with PUT request. I know how to do that but in Android I don't know it.
The API docs gives a sample request.
PUT /images/upload/image_title HTTP/1.1
Host: some.domain.com
Date: Thu, 17 Jul 2008 14:56:34 GMT
X-SE-Client: test-account
X-SE-Accept: xml
X-SE-Auth: 90a6d325e982f764f86a7e248edf6a660d4ee833
bytes data goes here
I have written some code but it gives me error.
HttpClient httpclient = new DefaultHttpClient();
HttpPut request = new HttpPut(Host + "images/upload/" + Name + "/");
request.addHeader("Date", now);
request.addHeader("X-SE-Client", X_SE_Client);
request.addHeader("X-SE-Accept", X_SE_Accept);
request.addHeader("X-SE-Auth", Token);
request.addHeader("X-SE-User", X_SE_User);
// I feel here is something wrong
File f = new File(Path);
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("photo", new FileBody(f));
request.setEntity(entity);
HttpResponse response = httpclient.execute(request);
HttpEntity resEntityGet = response.getEntity();
String res = EntityUtils.toString(resEntityGet);
Is there something wrong I am doing?
try something similar to
try {
URL url = new URL(Host + "images/upload/" + Name + "/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("PUT");
// etc.
} catch (Exception e) { //handle the exception !}
EDIT - another and better option:
Using the built-in HttpPut is recommended - examples see http://massapi.com/class/org/apache/http/client/methods/HttpPut.java.html
EDIT 2 - as requested per comment:
Use setEntity method with for example new FileEntity(new File(Path), "binary/octet-stream"); as param before calling execute to add a file to the PUT request.
The following code works fine for me:
URI uri = new URI(url);
HttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost(uri);
File file = new File(filename);
MultipartEntity entity = new MultipartEntity();
ContentBody body = new FileBody(file, "image/jpeg");
entity.addPart("userfile", body);
post.setEntity(entity);
HttpResponse response = httpclient.execute(post);
HttpEntity resEntity = response.getEntity();
I have some code to post an image to my php script that uploads to a database, when it adds to the database the file type is application/oct???? (what is this)
is there anyway of changing this to a jpg file at the android stage?
Below is my code
HttpClient client = new DefaultHttpClient();
String postURL = "http://10.0.2.2:90/mobileupload3.php";
HttpPost post = new HttpPost(postURL);
FileBody bin = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("image", bin);
reqEntity.addPart("name", new StringBody(enteredName));
reqEntity.addPart("gender", new StringBody(radio));
reqEntity.addPart("cat", new StringBody(radio2));
reqEntity.addPart("lat", new StringBody(lat));
reqEntity.addPart("lon", new StringBody(lon));
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
Log.i("RESPONSE",EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
application/oct (I assume you mean application/octet-stream) is a MIME type for a general binary file.
Without more information on your method of upload, I believe that the other part of your question has already been answered on SO here.
I've been looking into this for the last day or two and can not seem to find a solution to my issue. I am trying to post an image to a server using httppost.
I have tried two ways of doing this and both complete the post but with no content i.e. the content length is 0.
The first is as follows:
String url = "MYURL";
HttpClient httpClient = new DefaultHttpClient();
try {
httpClient.getParams().setParameter("http.socket.timeout", new Integer(90000)); // 90 second
HttpPost post = new HttpPost(url);
File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(SDCardRoot,"/DCIM/100MSDCF/DSC00004.jpg");
FileEntity entity;
entity = new FileEntity(file,"binary/octet-stream");
entity.setChunked(true);
post.setEntity(entity);
post.addHeader("Header", "UniqueName");
HttpResponse response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
Log.e("Here","--------Error--------Response Status line code:"+response.getStatusLine());
}else {
// Here every thing is fine.
}
HttpEntity resEntity = response.getEntity();
if (resEntity == null) {
Log.e("Here","---------Error No Response!!-----");
}
} catch (Exception ex) {
Log.e("Here","---------Error-----"+ex.getMessage());
ex.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown();
}
and the second is:
String url = "MYURL";
//File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(Environment.getExternalStorageDirectory(),"/DCIM/100MSDCF/DSC00004.jpg");
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true);
// Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
Log.d("finishing", "The try catch function");
} catch (Exception e) {
// show error
}*/
As you can see I have hardcoded a path to a specific image, this is to be dynamic when I get it up and running.
Can anyone see what i'm doing wrong? Am I leaving out something? I know I use setChunked and setContenttype - is there a setContent option?
Any help would be grately appreciated.
Thanks,
jr83.
You can use upload your image by sending multipart messages; you might find this discussion useful.