Send text file to distant server in Android - android

I am trying to send a file from an android phone to a distant server. This is the code I used:
public void sendFile() {
try {
// HttpClient
HttpClient client = new DefaultHttpClient();
// post header
HttpPost post = new HttpPost("http://example.com/get_data.php");
// add your data
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
File folder = this.mContext.getFilesDir();
File file = new File(folder, "test.txt");
if (file.exists()) {
Log.d(TAG, "File exists : " + folder.listFiles()[0].toString());
}
builder.addPart("file", new FileBody(file));
builder.addBinaryBody("file", file);
HttpEntity entity = builder.build();
post.setEntity(entity);
HttpResponse response = client.execute(post);
HttpEntity Httpentity = response.getEntity();
Log.v("result", EntityUtils.toString(Httpentity));
} catch (Exception e) {
e.printStackTrace();
}
}
This code should be correct since I found similar examples here and there. The problem occurs when I build the MultipartEntityBuilder:
HttpEntity entity = builder.build();
I get this error:
Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/util/Args;
at org.apache.http.entity.mime.content.AbstractContentBody.<init>(AbstractContentBody.java:48)
at org.apache.http.entity.mime.content.FileBody.<init>(FileBody.java:96)
at org.apache.http.entity.mime.MultipartEntityBuilder.addBinaryBody(MultipartEntityBuilder.java:141)
at org.apache.http.entity.mime.MultipartEntityBuilder.addBinaryBody(MultipartEntityBuilder.java:146)
at com.example.kevin.recordacceleration.Accelerometer.sendFile(Accelerometer.java:149)
The file I'm trying to send is in the internal memory, and I check its existence: it exists.
Here are the libraries that I added:
It is not the latest version because I read on an other topic that this version of httpmime and httpclient should work

Your app is missing commons-codec and commons-logging on which HttpCore and HttpClient depends. Httpmime depends on HttpClient.

Related

MultipartEntity image upload not working

I want to upload image using MultipartEntity , I have added all external jar files.
But when I try to use below code I get class not found error , and image is not able to upload.
Now I restart eclipse , Now I get error like
Unable to execute dex: Multiple dex files define Lorg/apache/http/entity/mime/FormBodyPart;
Conversion to Dalvik format failed: Unable to execute dex: Multiple dex files define Lorg/apache/http/entity/mime/FormBodyPart;
Below is my php file and java code.
<?php
$photo = $_FILES['photo']['name'];
if(!empty($_FILES['photo']['name']))
{
move_uploaded_file($_FILES['photo']['tmp_name'], "User_files/".$_FILES['photo']['name']);
}
?>
.
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
File file = new File(Environment.getExternalStorageDirectory()+"/a.png");
//Log.d(TAG, "UPLOAD: setting up multipart entity");
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
//Log.d(TAG, "UPLOAD: file length = " + file.length());
//Log.d(TAG, "UPLOAD: file exist = " + file.exists());
mpEntity.addPart("photo", new FileBody(file, "image/png"));
//mpEntity.addPart("id", new StringBody("1"));
httppost.setEntity(mpEntity);
HttpResponse response;
try {
response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
}
if (resEntity != null) {
resEntity.consumeContent();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Trouble Uploading Image from Android to Rails Server Using PaperClip

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.

Android File Upload Using HTTP PUT

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();

Set image type in android

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.

Android Multipart Upload

As part of my Android app, I'd like to upload bitmaps to be remotely stored. I have simple HTTP GET and POST communication working perfectly, but documentation on how to do a multipart POST seems to be as rare as unicorns.
Furthermore, I'd like to transmit the image directly from memory, instead of working with a file. In the example code below, I'm getting a byte array from a file to be used later on with HttpClient and MultipartEntity.
File input = new File("climb.jpg");
byte[] data = new byte[(int)input.length()];
FileInputStream fis = new FileInputStream(input);
fis.read(data);
ByteArrayPartSource baps = new ByteArrayPartSource(input.getName(), data);
This all seems fairly clear to me, except that I can't for the life of me find out where to get this ByteArrayPartSource. I have linked to the httpclient and httpmime JAR files, but no dice. I hear that the package structure changed drastically between HttpClient 3.x and 4.x.
Is anyone using this ByteArrayPartSource in Android, and how did they import it?
After digging around in the documentation and scouring the Internet, I came up with something that fit my needs. To make a multipart request such as a form POST, the following code did the trick for me:
File input = new File("climb.jpg");
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://localhost:3000/routes");
MultipartEntity multi = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
String line;
multi.addPart("name", new StringBody("test"));
multi.addPart("grade", new StringBody("test"));
multi.addPart("quality", new StringBody("test"));
multi.addPart("latitude", new StringBody("40.74"));
multi.addPart("longitude", new StringBody("40.74"));
multi.addPart("photo", new FileBody(input));
post.setEntity(multi);
HttpResponse resp = client.execute(post);
The HTTPMultipartMode.BROWSER_COMPATIBLE bit is very important. Thanks to Radomir's blog on this one.
try this:
HttpClient httpClient = new DefaultHttpClient() ;
HttpPost httpPost = new HttpPost("http://example.com");
MultipartEntity entity = new MultipartEntity();
entity.addPart("file", new FileBody(file));
httpPost.setEntity(entity );
HttpResponse response = null;
try {
response = httpClient.execute(httpPost);
} catch (ClientProtocolException e) {
Log.e("ClientProtocolException : "+e, e.getMessage());
} catch (IOException e) {
Log.e("IOException : "+e, e.getMessage());
}
Perhaps you can do following step to import library into your Android.
requirement library
- apache-mime4j-0.6.jar
- httpmime-4.0.1.jar
Right click your project and click properties
select java build path
select tab called "Order and Export"
Apply it
Fully uninstall you apk file with the adb uninstall due to existing apk not cater for new library
install again your apk
run it
Thanks,
Jenz
I'm having the same problem. I'm trying to upload an image through MultiPart Entity and it seens that the several updates on HttpClient/MIME are cracking everything. I'm trying the following code, falling with an Error "NoClassDefFoundError":
public static void executeMultipartPost(File image, ArrayList<Cookie> cookies, String myUrlToPost) {
try {
// my post instance
HttpPost httppost = new HttpPost(myUrlToPost);
// setting cookies for the connection session
if (cookies != null && cookies.size() > 0) {
String cookieString = "";
for (int i=0; i<cookies.size(); ++i) {
cookieString += cookies.get(i).getName()+"="+cookies.get(i).getValue()+";";
}
cookieString += "domain=" + BaseUrl + "; " + "path=/";
httppost.addHeader("Cookie", cookieString);
}
// creating the http client
HttpClient httpclient = new DefaultHttpClient();
// creating the multientity part [ERROR OCCURS IN THIS BELLOW LINE]
MultipartEntity multipartEntity = new MultipartEntity();
multipartEntity.addPart("photoupload", new FileBody(image));
httppost.setEntity(multipartEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
} catch (Exception e) {}
}
This method is fully compilable and uses the httpclient-4.0.1.jar and httpmime-4.2.jar libs, but again, I remember that it crashs in the commented line for me.

Categories

Resources