I want to send an image from the android client to the Django server using Http Post. The image is chosen from the gallery. At present, I am using list value name Pairs to send the necessary data to the server and receiving responses from Django in JSON. Can the same approach be used for images (with urls for images embedded in JSON responses)?
Also, which is a better method: accessing images remotely without downloading them from the server or downloading and storing them in a Bitmap array and using them locally? The images are few in number (<10) and small in size (50*50 dip).
Any tutorial to tackle these problems would be much appreciated.
Edit: The images chosen from the gallery are sent to the server after scaling it to required size.
I'm going to assume that you know the path and filename of the image that you want to upload. Add this string to your
NameValuePair
usingimage
as the key-name.Sending images can be done using the HttpComponents libraries. Download the latest HttpClient (currently 4.0.1) binary with dependencies package and copy
apache-mime4j-0.6.jar
andhttpmime-4.0.1.jar
to your project and add them to your Java build path.You will need to add the following imports to your class.
Now you can create a
MultipartEntity
to attach an image to your POST request. The following code shows an example of how to do this:I hope this helps you a bit in the right direction.
The loopj library can be used straight-forward for this purpose:
http://loopj.com/
Since
MultipartEntity
has been deprecated. Please see the code below.I struggled a lot trying to implement posting a image from Android client to servlet using httpclient-4.3.5.jar, httpcore-4.3.2.jar, httpmime-4.3.5.jar. I always got a runtime error. I found out that basically you cannot use these jars with Android as Google is using older version of HttpClient in Android. The explanation is here http://hc.apache.org/httpcomponents-client-4.3.x/android-port.html. You need to get the httpclientandroidlib-1.2.1 jar from android http-client library. Then change your imports from or.apache.http.client to ch.boye.httpclientandroidlib. Hope this helps.
I usually do this in the thread handling the json response:
If you need to do transformations on the image, you'll want to create a Drawable instead of a Bitmap.