This is what I am doing to upload a video to a server:
email
gameId
source
uploadedfile
are the parameters that have to be sent. email, gameId and source are string values,
whereas uploadedfile is the filebody to be uploaded.
Running this code gives response error0.
HttpClient client = new DefaultHttpClient();
String postURL = GlobalConfig.url+"uploadBlogData.php";
HttpPost post = new HttpPost(postURL);
FileBody bin = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("email", new StringBody(GlobalConfig.pref.getString(GlobalConfig.KEY_User_Emailid,""), "text/plain", Charset.forName( "UTF-8")));
reqEntity.addPart("gameId", new StringBody(GlobalConfig.pref.getString(
GlobalConfig.KEY_Game_Created_id,
""), "text/plain", Charset.forName( "UTF-8")));
reqEntity.addPart("source", new StringBody("phone", "text/plain", Charset.forName("UTF-8")));
reqEntity.addPart("uploadfile", bin);
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
Log.d("resP",GlobalConfig.getStringFromResponse(response));
HttpEntity resEntity = response.getEntity();
Related
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("http://192.168.150.101:8080/TDIDP/ServletImagen");
File file = new File("C:\\pw\\proyectos\\TDIDP\\a.png");
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/png");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
I have this code that sends images to a Servlet, but the problem is that now MultipartEntitiy is not available for Android since it is obsolete, how can I use MultiPartEntityBuilder to do a multipar?
how can I use MultiPartEntityBuilder to do a multipart.
HttpClient is not supported any more in sdk 23, if you use it, you need to work around much. You have to use URLConnection
You can see MultipartUtility in this link https://github.com/RecastAI/SDK-Android/blob/master/src/main/java/ai/recast/sdk_android/MultipartUtility.java.
I asked this question before but I don't get answer. I want to upload image from android application to django. this is my android code:
public void upload(String filepath) throws IOException{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(SoberRequest.UPLOAD_IMAGE_URL);
File file = new File(filepath);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody cbFile = new FileBody(file, "image/jpeg");
builder.addPart("image", cbFile);
HttpEntity mpEntity = builder.build();
httppost.setEntity(mpEntity);
httppost.setHeader("enctype", "multipart/form-data");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
...
}
and this is my djnago code to get image:
#csrf_exempt
def get_image(request):
if request.method == "POST":
destination_path = open("Images/filan.jpg", "wb+")
print(request.FILES)
image = request.FILES['image']
destination_path.write(image)
destination_path.close()
json_data = {"status": SUCCESSFUL}
return HttpResponse(json.dumps(json_data), mimetype=json_mimeType)
else:
json_data = {"status": ERROR}
return HttpResponse(json.dumps(json_data), mimetype=json_mimeType)
but when I print request.FILES , it is empty. but if I print request.body I see a field that name is "image" like this : b'--Z7unui4m0r4igQdqkvmj7DQ5rm46GmZDm\r\nContent-Disposition: form-data; name="image"\r\n\r\n\xff\xd.....". also if I set header in my android app like this :
httppost.addHeader("Content-type", "multipart/form-data")
I get another error in my django : "Invalid boundary in multipart: None"
what is problem ?
I want to upload image from android app to djnago. this is my android code to upload image:
public void upload(String filepath) throws IOException{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(SoberRequest.UPLOAD_IMAGE_URL);
File file = new File(filepath);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody cbFile = new FileBody(file, "image/jpeg");
builder.addPart("image", cbFile);
HttpEntity mpEntity = builder.build();
httppost.setEntity(mpEntity);
httppost.setHeader("enctype", "multipart/form-data");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
...
}
and this is my django code to get and save image:
#csrf_exempt
def get_image(request):
try:
if request.method == "POST":
destination_path = open("Images/filan.jpg", "wb+")
print(request.FILES)
image = request.FILES['image']
destination_path.write(image)
destination_path.close()
json_data = {"status": SUCCESSFUL}
return HttpResponse(json.dumps(json_data), mimetype=json_mimeType)
else:
json_data = {"status": ERROR}
return HttpResponse(json.dumps(json_data), mimetype=json_mimeType)
when i print request.FILES, it is empty : . and django raise this MultiValueDictKeyError exeption. what is problem? thanks
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);
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