Upload image to server using android - android

I am trying to upload an image to server.For that I have added jar files like apache-mime4j,http client,httpcore and httpmime.
And my code is as follows..
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
MultipartEntity multiPart = new MultipartEntity();
multiPart.addPart("my_picture", new FileBody(new File(imagePath.toString())));
httpPost.setEntity(multiPart);
HttpResponse res = httpClient.execute(httpPost);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String json = reader.readLine();
JSONTokener tokener = new JSONTokener(json);
JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
JSONArray data = object.getJSONArray("data");
System.out.println("posted finalResult"+data);
if (responseEntity != null) {
responseEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
The problem is that I am getting an error at the line
multiPart.addPart("my_picture", new FileBody(new File(imagePath.toString())));
And on clicking that error I am getting "Configure build path".
Anyone please tell me what is wrong in my code.
Thanx in advance.

Related

Send Image and String by using MultipartEntity

I am working on an app that allows the user upload an image by using HttpPost method. I use MultipartEntity and therefore I added the libraries apache-mime4j-0.6.1.jar, httpclient-4.3.1.jar, httpcore-4.3.1.jar and httpmime-4.2.1.jar into my app. My upload code is like below:
public String uploadFile() throws Exception
{
String result = "";
try
{
HttpResponse response = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(_url);
request.setHeader("Accept", "application/json");
File file=new File(filePath);
String fileName=file.getName();
MultipartEntity imageEntity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,null,Charset.forName("UTF-8"));
imageEntity.addPart("imageName", new StringBody(fileName));
imageEntity.addPart("image", new FileBody(file, "application/octet-stream"));
request.setEntity(imageEntity);
response = httpClient.execute(request);
InputStream dataStream = response.getEntity().getContent();
BufferedReader dataReader = new BufferedReader(new InputStreamReader(dataStream));
String line = "";
while ((line = dataReader.readLine()) != null)
result+=line;
}
catch (Exception e)
{
}
return result;
}
I get response from my server but in my web service code Request.Files has no file. If I change the line:
MultipartEntity imageEntity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,null,Charset.forName("UTF-8"));
to
MultipartEntity imageEntity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
app is in process for a long time (about 3-4 minutes) and throws error. This is caused if I add an image. If I send only StringBody without FileBody, I get response from server and Request.Files in my webservice code return file count correctly. How can I fix this problem and upload image correctly? Any suggestion?

Android Json Get URL STOPPED

I just started the topic to get data from a JSON OpenData and visualize via my phone.
I followed this tutorial and it has worked all :)
https://www.learn2crack.com/2013/10/android-asynctask-json-parsing-example.html
The url whew i get the datas is :
http:// + api.learn2crack.com/android/json/ (sorry for that, I don't have a good reputation :) )
Then I wanted to try a Opendata me and my android application stops, the url is:
http://ckan.opendata.nets.upf.edu/storage/f/2013-11-30T16%3A49%3A59.118Z/london.json
You can see it's the same and I only change the name of URL in the code.
You know if the problem is because of the OpenData? and I need some permission? Because when I execute the second part my app stopped
Here, this will work. I am using Strict Policy but normally you should use Async. Please google this as to why we should use Async instead of Strict Policy. This is irrelevant here
When i am using HttpPost to get your json from url, i am getting these errors :-
405 Method Not Allowed
The method POST is not allowed for this resource.
You cannot POST a file
so i am using HttpGet :-
String url = "http://ckan.opendata.nets.upf.edu/storage/f/2013-11-30T16:49:59.118Z/london.json";
try{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
//HttpPost httpPost = new HttpPost(url);
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
JSONObject jObj = new JSONObject(sb.toString());
JSONArray json2 = json.getJSONArray("user");
for (int i = 0; i < json2.length(); i++) {
JSONObject c = json2.getJSONObject(i);
}
}
catch (Exception e) {
e.printStackTrace();
}

Uploading pictures with additional data to php

I want to upload a photo from the phone with some data like name and email.
From an Android device I know how to upload a photo and I know how to send data between the phone and the server but how do you do both at the same time?
Should I do them separately?
In your case you should use the MultipartEntity class,
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("name", new StringBody(name));
reqEntity.addPart("email", new StringBody(email));
if(imagePath.trim().length() != 0) {
reqEntity.addPart("profilePic", new FileBody(new File(imagePath)));
}
HttpClient hc = new DefaultHttpClient();
HttpPost postMethod = new HttpPost(urlString);
HttpEntity resEntity;
HttpResponse response = null;
postMethod.setEntity(reqEntity);
response = hc.execute(postMethod);
resEntity = response.getEntity();
response_str = EntityUtils.toString(resEntity);

Upload image from android to python appengine blobstore

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

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.

Categories

Resources