How to take a photo and send to HTTP POST request with Android?
This link should be more than sufficient for clicking, saving and getting path of an image:
Capture Images
This is the class i wrote for uploading images via HTTP POST:
public class MultipartServer {
private static final String TAG = "MultipartServer";
private static String crlf = "\r\n";
private static String twoHyphens = "--";
private static String boundary = "*****";
private static String avatarPath = null;
public static String postData(URL url, List<NameValuePair> nameValuePairs) throws IOException {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(10000);
connection.setConnectTimeout(15000);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Cache-Control", "no-cache");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
String avatarName = null;
StringBuilder query = new StringBuilder();
boolean first = true;
for (NameValuePair pair : nameValuePairs) {
if (first)
first = false;
else
query.append("&");
query.append(URLEncoder.encode(pair.getName(), "UTF-8"));
query.append("=");
query.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
if ((avatarName = pair.getName()).equals("avatar")) {
avatarPath = pair.getValue();
}
}
FileInputStream inputStream;
OutputStream outputStream = connection.getOutputStream();
DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
dataOutputStream.writeBytes(query.toString());
// Write Avatar (if any)
if(avatarName != null && avatarPath != null) {
dataOutputStream.writeBytes(twoHyphens + boundary + crlf);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + avatarName + "\";filename=\"" + new File(avatarPath).getName() + "\";" + crlf);
dataOutputStream.writeBytes(crlf);
/*Bitmap avatar = BitmapFactory.decodeFile(avatarPath);
avatar.compress(CompressFormat.JPEG, 75, outputStream);
outputStream.flush();*/
inputStream = new FileInputStream(avatarPath);
byte[] data = new byte[1024];
int read;
while((read = inputStream.read(data)) != -1)
dataOutputStream.write(data, 0, read);
inputStream.close();
dataOutputStream.writeBytes(crlf);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + crlf);
}
dataOutputStream.flush();
dataOutputStream.close();
String responseMessage = connection.getResponseMessage();
Log.d(TAG, responseMessage);
InputStream in = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
StringBuilder response = new StringBuilder();
char []b = new char[512];
int read;
while((read = bufferedReader.read(b))!=-1) {
response.append(b, 0, read);
}
connection.disconnect();
Log.d(TAG, response.toString());
return response.toString();
}
}
Usage is quite simple: call this static method and pass the path of your image like:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("avatar", imagePath));
and finally:
MultipartServer.postData(url, nameValuePairs);
and don't forget to call this function in a separate thread or you'll get NetworkOnMainThreadException.. :)
Update
I'd recommend not to reinvent the wheel & use OkHttp instead. Do checkout the Recipes page. Disclaimer: I'm not a contributor to the project, but I love it. Thanks to Square team.
Android: Sending an image through POST
This is what I did yesterday, maybe it will help
Bitmap bitmapOrg = images.get(0);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
String upload_url = prepare_upload_url();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] data = bao.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(upload_url);
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
//Set Data and Content-type header for the image
entity.addPart("file",
new ByteArrayBody(data, "image/jpeg", "file"));
postRequest.setEntity(entity);
try {
HttpResponse response = httpClient.execute(postRequest);
//Read the response
String jsonString = EntityUtils.toString(response.getEntity());
Log.v(ProgramConstants.TAG, "after uploading file "
+ jsonString);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Sending images using Http Post
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
using image
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
and httpmime-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.
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
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:
public void post(String url, List<NameValuePair> nameValuePairs) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for(int index=0; index < nameValuePairs.size(); index++) {
if(nameValuePairs.get(index).getName().equalsIgnoreCase("image")) {
// If the key equals to "image", we use FileBody to transfer the data
entity.addPart(nameValuePairs.get(index).getName(), new FileBody(new File (nameValuePairs.get(index).getValue())));
} else {
// Normal string data
entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
} catch (IOException e) {
e.printStackTrace();
}
}
I hope this helps you a bit in the right direction.
Upload Image to server in android by Httppost
You can upload image to the server using http post multi-part. Here is the link which will help you out.
https://vikaskanani.wordpress.com/2011/01/11/android-upload-image-or-file-using-http-post-multi-part/
http://www.codejava.net/java-se/networking/upload-files-by-sending-multipart-request-programmatically
And one more way to uploading image is, convert it into Base64 and than upload. Check the below link.
Android upload image to server using base64
Android - Sending Image file to the Server DB with POST Request
This is another way send image on server
public class UploadImage extends Activity {
InputStream inputStream;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_image_upload);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeBytes(byte_arr);
ArrayList<namevaluepair> nameValuePairs = new ArrayList<namevaluepair>();
nameValuePairs.add(new BasicNameValuePair("image",image_str));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.0.23/Upload_image_ANDROID/upload_image.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String the_string_response = convertResponseToString(response);
Toast.makeText(UploadImage.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();
}catch(Exception e){
Toast.makeText(UploadImage.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();
System.out.println("Error in http connection "+e.toString());
}
}
public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{
String res = "";
StringBuffer buffer = new StringBuffer();
inputStream = response.getEntity().getContent();
int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
Toast.makeText(UploadImage.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show();
if (contentLength < 0){
}
else{
byte[] data = new byte[512];
int len = 0;
try
{
while (-1 != (len = inputStream.read(data)) )
{
buffer.append(new String(data, 0, len)); //converting to string and appending to stringbuffer…..
}
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
inputStream.close(); // closing the stream…..
}
catch (IOException e)
{
e.printStackTrace();
}
res = buffer.toString(); // converting stringbuffer to string…..
Toast.makeText(UploadImage.this, "Result : " + res, Toast.LENGTH_LONG).show();
//System.out.println("Response => " + EntityUtils.toString(response.getEntity()));
}
return res;
}
}
Send picture from Android app to server http post
1) In first side decode bitmap into byte array
2) In other side - create bitmap from byte array.
BitmapFactory documentation
Bitmap TO byte array
Bitmap FROM byte array
How to post a simple image from Android to server using post method
Following is a scenario that indicates how image transforms from one format to another format and finally back to original format.
try following code
Android side
private void uploadToServer(byte[] data) {
Bitmap bitmapOrg = BitmapFactory.decodeByteArray(data, 0, data.length);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] ba = bao.toByteArray();
String ba1 = Base64.encodeBytes(ba);
final ArrayList<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image", ba1));
Thread t = new Thread() {
@Override
public void run() {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://www.yoururl.com");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
// HttpEntity entity = response.getEntity();
// is = entity.getContent();
// String the_string_response =
// convertResponseToString(response);
// Log.e("log_tag", "Image Uploaded "+the_string_response);
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
}
};
}
Server side
<?php
$base=$_REQUEST['image'];
echo $base;
// base64 encoded utf-8 string
$binary=base64_decode($base);
// binary, utf-8 bytes
header('Content-Type: bitmap; charset=utf-8');
// print($binary);
//$theFile = base64_decode($image_data);
$file = fopen('test.jpg', 'wb');
fwrite($file, $binary);
fclose($file);
echo '<img src=test.jpg>';
?>
Complete Tutorial
Related Topics
Does PHP Optimize Tail Recursion
Woocommerce Add to Cart Button Redirect to Checkout
Write a Text File and Force to Download with PHP
Do PHP Pdo Prepared Statements Need to Be Escaped
Best Way to Periodically Execute a PHP Script
Google Calendar API Service Account Error
Add a Quantity Field to Ajax Add to Cart Button on Woocommerce Shop Page
PHP .Htaccess -> Pretty Url (In Reverse)
PHP Day of Week Numeric to Day of Week Text
Will PHP Script Be Executed After Header Redirect
PHP Dom Get Nodevalue HTML? (Without Stripping Tags)
Symfony2: How to Access Service from Template
Best Way to Internationalize Simple PHP Website