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
Related
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'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.
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
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();
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();