I need to upload a bitmap image to my server but it takes a lot of time while uploading. I use base64 to encode the image and decode it while adding it to the database as Blob.
I want to know what is the other alternative way to upload an image and which one is more efficient.
Here what I have been trying:
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1);
HttpConnectionParams.setConnectionTimeout(params, 20000);
HttpConnectionParams.setSoTimeout(params, 15000);
DefaultHttpClient httpClient = new DefaultHttpClient(params);
HttpPost httpPost = new HttpPost(url);
namevaluepair.add(new BasicNameValuePair("icon", getStringDrawing(bmIcon)))
httpPost.setEntity(new UrlEncodedFormEntity(namevaluepair));
httpClient.execute(httpPost);
public static String getStringDrawing(Bitmap bm) {
String image_str = "";
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byte[] byte_arr;
bm.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte_arr = stream.toByteArray();
image_str = Base64.encodeBytes(byte_arr);
} catch (NullPointerException e) {
}
return image_str;
}
In PHP I tried to save it in Blob and in folder here some of the codes:
$Drawing = $_POST {'drawing'};
$buffer = base64_decode($Drawing);
$file = fopen("PostImage/P".$ID.".png", 'wb');
fwrite($file, $buffer);
fclose($file);
The second try:
$Drawing = $_POST {'drawing'};
$buffer = base64_decode($Drawing);
$buffer = mysql_real_escape_string($buffer);
$query = "INSERT INTO `drawposts` (`PostID`, `UserID`,`DatePost`, `Drawing`) VALUES (NULL,'$UserID','$Date','$buffer')";
$sth = mysql_query($query);
Look at the FileEntity . Something like
File Picture = new File("/path/to/jpg");
FileEntity f = new FileEntity(picture,"application/octet-stream");
HttpPost post = new HttpPost("my URL");
post.setEntity(f);
post.setHeader("Content-type", "application/octet-stream");
Related
my app contains a registration form with some fields like firstName,lastName,email,password and image which are to be uploaded into the server with the post method (whatever the concept like Multipart).
/*MultipartEntity entity2 =new MultipartEntity();
entity2.addPart("pic", image);
httppost.setEntity(entity2);*/
/* Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon); 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);*/
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("first_name",firstName));
nameValuePairs
.add(new BasicNameValuePair("last_name",lastName));
nameValuePairs.add(new BasicNameValuePair("email",email));
nameValuePairs
.add(new BasicNameValuePair("password",password));
nameValuePairs
.add(new BasicNameValuePair("pic",image));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
/*
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entityBuilder.addTextBody("first_name",firstName);
entityBuilder.addTextBody("last_name",lastName);
entityBuilder.addTextBody("email",email);
entityBuilder.addTextBody("password",password);
File file = new File(image);
if(file != null)
{
entityBuilder.addBinaryBody("pic", file);
}
HttpEntity ent = entityBuilder.build();
httppost.setEntity(ent);*/
/* HttpResponse response = client.execute(post);
HttpEntity httpEntity = response.getEntity();
result = EntityUtils.toString(httpEntity);
Log.v("result", result);*/
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity=response.getEntity();
InputStream is = entity.getContent();
String response_ = convertStreamToString(is);
System.out.println("Successfully posted to server "+response_);
return response_;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
lastname = editLastName.getText().toString();
email = editEmail.getText().toString();
password = editPassword.getText().toString();
Log.e("path", "----------------" + picturePath);
// Image
/* Bitmap bm = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] ba = bao.toByteArray();
ba1 = Base64.encodeToString(ba, Base64.DEFAULT);
Log.e("base64", "-----" + ba1);*/
Bitmap bitmapOrg= BitmapFactory.decodeFile(imgPath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encode(ba, Base64.DEFAULT).toString();
System.out.println("image before RegisterAsync "+ba1);
// connection object creation
detector = new ConnectionDetector(getApplicationContext());
RegisterDownloadHelper();
if (detector.isConnectingToInternet()){
new RegisterAsync(MainActivity.this,
RegisterDownloadHelper,url,firstname,lastname,email,password,fileName)
.execute();
} else {
manager.showAlertDialog(MainActivity.this, "ALERT",
"Please Check The Internet Connection !", false);
}
The best way to do this is to implement an IntentService and notify status with broadcast intents. please checkout complete code from github
https://github.com/alexbbb/android-upload-service
let me know if you facing any problem to integrate this code
//this Method call Intent Services
public static void uploadFile(Context context) {
Settings.openDataBase(context);
final String serverUrlString = "http://test/webservice.php";
final String fileToUploadPath = Settings.getProfilePicPath();
File fileObj = new File(fileToUploadPath);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(fileObj.getAbsolutePath(), bmOptions);
ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
Uri tempUri = getImageUri(context, decoded);
File finalFile = new File(getRealPathFromURI(context,tempUri));
final String paramNameString = "image";
final UploadRequest request = new UploadRequest(context, UUID.randomUUID().toString(), serverUrlString);
request.addParameter("type", "account_edit");
request.addParameter("username", Settings.getUserName());
request.addParameter("email", Settings.getUserEmail());
request.addParameter("user_id", Settings.getUserId());
request.addFileToUpload(finalFile.getAbsolutePath(), paramNameString, finalFile.getName(),
ContentType.APPLICATION_OCTET_STREAM);
request.setNotificationConfig(R.drawable.app_icon, context.getString(R.string.app_name),
context.getString(R.string.uploading), context.getString(R.string.upload_success),
context.getString(R.string.upload_error), false);
try {
UploadService.startUpload(request);
} catch (Exception exc) {
Toast.makeText(context, "Malformed upload request. " + exc.getLocalizedMessage(), Toast.LENGTH_SHORT)
.show();
}
}
I have encoded an image to base 64 as
Bitmap bitmapOrg= BitmapFactory.decodeFile(imagePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] byarray = bao.toByteArray();
String myimage=Base64.encodeBytes(byarray);
.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://10.1.1.5/connect/royal.php");
try{
List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
nameValuePairs.add(new BasicNameValuePair("IMAGE",myimage));
nameValuePairs.add(new BasicNameValuePair("FILENAME",trID));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String responseStr = EntityUtils.toString(response.getEntity());
Log.d("chddeck", responseStr);
JSONObject jsonObj = new JSONObject(responseStr);
int success = jsonObj.getInt("success");
if (success == 1) {
status="1";
}else if (success==0){
status="0";
}
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
in php, I have stored as:
$base = $_REQUEST['image'];
$filename = $_REQUEST['filename'];
$buffer=base64_decode($base);
$path = "upload/".$filename.".jpg";
$handle = fopen($path, 'wb');
$numbytes = fwrite($handle, $buffer);
fclose($handle);
$query = $link->prepare("UPDATE transaction evidenceimage=?,evidencename=? WHERE transactionID = '5'");
$values = array($path, $filename);
$query->execute($values);
$counts= $query->rowCount();
if ($counts>0)
{
$rowset = $query->fetchAll();
$response["comments"]=array();
$comments =array();
$response["success"]=1;
}
else{
$response["success"]=0;
}
echo json_encode($response);
Problem is, image is perfectly uploaded in the "upload/" directory in server. But not stored in mysql. In mysql - evidenceimage is set to be "BLOB. After this query, "BLOB-filenameB" is stored in the table, which appears to be only 1 KB.
Please could anybody suggest what am i doing wrong ??
To get the image in your android program I think you need to pass the path of image uploaded in your localhost or the server. And to get the image at your application try this:
UrlImageViewHelper.setUrlDrawable("your imageview name",
"your image path in localhost or server",
"optional image to display if not available in your drawable folder",
"cache duration");
you can get the library UrlImageViewHelper here:
http://www.koushikdutta.com/UrlImageViewHelper
We are working on an application which has 2 modules.
Android Application.
PHP Application
PHP backend application runs on an Apache Server with Centos Server.
Android application basically clicks images, send to the server along with gps coordinates etc form information.
Now the problem arises when the image file is created on the server. When android app calls the url the '&' character is replaced by & amp;, sometimes even by & amp;& amp; and this problem repeats in some of the cases. Once this conversion thing happens, image file is not created properly.
How it can be resolved?
Same code was working alright from past year, this problem begin to arise from last month only....
Following is the code for saving the images at server end :
foreach($_POST as $key => $value) {
$_POST[$x] = $value;
}
$base=$_REQUEST['image'];
$nm=$_REQUEST['name'];
$binary=base64_decode($base);
if(file_exists("uploaded_images/".$nm.".jpg")) {
unlink("uploaded_images/".$nm.".jpg");
}
header('Content-Type: bitmap; charset=utf-8');
$str="uploaded_images/".$nm.".jpg";
$file = fopen($str, 'wb');
fwrite($file, $binary);
fclose($file);
chmod($file,0777);
$ok=1;
echo $ok;
Following is the error log which is encountered if image is not properly saved.
PHP Notice: Undefined index: name in /var/www/html/cbd/def/filesubmitnew.php
Note : filesubmitnew.php is the file name of the above code.
In Android Application for this is how the url is called:
To Create image:
if(buttontext.equals("Img1")) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
v.setImageBitmap(bitmap);
buttontext="";
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, stream);
byte [] byte_arr = stream.toByteArray();
String str1 = Base64.encodeBytes(byte_arr);
System.out.println(""+str1);
if(feuser.equals("offline_access")){
System.out.println("++==--SD CARD");
File externalStorage = Environment.getExternalStorageDirectory();
File folder = new File(externalStorage.getAbsolutePath() +mainFolder + caseId);
if (!folder.exists()) {
folder.mkdir();
}
File pictureFile = new File(externalStorage.getAbsolutePath()+mainFolder+caseId, "1.jpg");
System.out.println(pictureFile);
pictureFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(pictureFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(str1);
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Done writing SD "+pictureFile,Toast.LENGTH_SHORT).show();
}
else {
Intent i = new Intent ("com.keyboardlabs.newbankge.CameraUploadService");
try {
i.putExtra("imageparams", str1);
i.putExtra("ref_id", caseId);
i.putExtra("imageId", "1");
i.putExtra("CaseType",caseType);
}
catch (Exception e) {
e.printStackTrace();
}
getApplicationContext().startService(i);
}
Following is the camerauploadservice
protected void onHandleIntent(Intent arg0) {
String imageDataBase64encoded = arg0.getStringExtra("imageparams");
String caseID = arg0.getStringExtra("ref_id");
String imageId = arg0.getStringExtra("imageId");
String caseType =arg0.getStringExtra("CaseType");
System.out.println("image_ref="+caseID+"iamgeID="+imageId+"caseType="+caseType+" URL="+URL);
callWebService(imageDataBase64encoded,caseID,imageId,caseType);
}
public void callWebService(String imageData,String refId,String imageId,String caseType){
HttpClient httpclient = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",imageData));
nameValuePairs.add(new BasicNameValuePair("ref_id",refId));
nameValuePairs.add(new BasicNameValuePair("imageId",imageId));
nameValuePairs.add(new BasicNameValuePair("CaseType",caseType));
try{
httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String the_string_response = convertResponseToString(response);
System.out.println( "Response= " + the_string_response);
}catch(Exception e){
System.out.println( "0" + e.getMessage());
System.out.println("Error in http connection "+e.toString());
}
httpclient.getConnectionManager().shutdown();
}
I'm trying to upload an image and some text via MultipartEntity.
I can upload and receive the image, but when I try to add a Stringbody I cannot seem to receive it.
Here's my android code
imports ETC...
public void oncreate(){
.....
nameValuePairs.add(new BasicNameValuePair("image", exsistingFileName));
nameValuePairs.add(new BasicNameValuePair("title", "title"));
}
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")) {
System.out.println("post - if");
// 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 {
System.out.println("post - else");
// Normal string data
entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));
}
}
System.out.println("post - done" + entity);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
} catch (IOException e) {
e.printStackTrace();
}
}
And my php:
<?php
$uploads_dir = 'uploads/';
$uploadname = $_FILES["image"]["name"];
$uploadtitle = $_FILES["title"]["title"];
move_uploaded_file($_FILES['image']['tmp_name'], $uploads_dir.$uploadname);
file_put_contents($uploads_dir.'juhl.txt', print_r($uploadtitle, true));
?>
I've been around the other questions about MultipartEntity, but cannot seem to find the answer. I've tried sending just the Stringbody, but didn't have any succs in that either. I think the problem is serverside (in the PHP) but any suggestions are welcome.
This is my first question in here - feel free to comment on form and clarity :-)
try this way ,
ByteArrayBody bab1 = bab11;
HttpClient httpClient = new DefaultHttpClient();
httpPost = new HttpPost("link.php?api_name=api");
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
// this is for String
try {
reqEntity.addPart("udid", new StringBody(UDID));
}
catch (Exception e)
{
}
// this is for image upload
try
{
reqEntity.addPart("file1", bab1);
} catch (Exception e)
{
}
// this is for video upload
try {
if (stPath1 != null) {
Log.e("path 1", stPath1);
Log.v("stDocType1", "video");
File file = new File(stPath1);
FileBody bin = new FileBody(file);
reqEntity.addPart("file1", bin);
}
} catch (Exception e) {
}
httpPost.setEntity(reqEntity);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
response = httpClient.execute(httpPost, responseHandler);
The problem was i the php.
When you receive Stringbody there is only one parametre(as opposed to filebody). So I removed the second parametre in $uploadtitle = $_FILES["title"]["title"]; and it worked
<?php
$uploads_dir = 'uploads/';
$uploadname = $_FILES["image"]["name"];
$uploadtitle = $_FILES["title"];
move_uploaded_file($_FILES['image']['tmp_name'], $uploads_dir.$uploadname);
file_put_contents($uploads_dir.'juhl.txt', print_r($uploadtitle, true));
?>
I hope this helps if you have the same problem.
------ Solution ------
The issue was on our server. It can only handle post requests if we put www in front of our domain name. So that's what caused the problems. I'm setting the first answer as THE answer since it worked once I sorted the URL out.
Original Question
I have a POST variable in my PHP script is always blank.
I've tried to change the variable's name, the content of the variable etc..
The problem has to reside in the java code, because when I var_dump() the request in php, it is null.
This is my scenario:
I let the user snap a photo, the photo is saved to the SD-card and I get the image's path, and eventually convert it to a Base64 string. I then want to post this base64 string to a php script that converts it back from Base64 and writes it as an image on my server's hard drive like so:
File f = new File(savedImagePath);
Bitmap bitmap = BitmapFactory.decodeFile(f.getPath());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 30, stream);
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeToString(byte_arr, Base64.DEFAULT);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://myURL/uploadImage.php");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("image", image_str));
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
On the server end, this is what my PHP script looks like:
<?php
$base = $_POST["image"];
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('uploaded_image.jpg', 'w');
fwrite($file, $binary);
fclose($file);
echo "script done executing";
?>
This is an example of a Base64 string I'm trying to post:
/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDABsSFBcUERsXFhceHBsgKEIrKCUlKFE6PTBCYFVlZF9VXVtqeJmBanGQc1tdhbWGkJ6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nRcC3bHKmrHeqtqe2MY7VaHTPNMkAcjj86AeaXpSYoRQoo7UDrRSYMKMe9LR6etGwgxSY5pfc0daYEUv3MnpTVX930/KpGGVwaZsK0h7lilpB+lA6VqSHTpzRR/Og8UxMO/NLSA55o6nrQMP1pfejFHWgA96B0pPalPXHFFhBRnik+lLQOwZ5o6UdKM/jQAoo70maO1AhT1pMcUg5pc0D0F70daT3paBAKKM0UDYDrSj+dJSigVw70d6QUtAw9zzRSZpc5+tMVwNL7UlH40gCgdaUcUlMApRRR2oAPeiijPFAIBQOtFFAbCikozRQADmlpBS0DAUUnfNL3oEFAo7YoxTAXvSdqO+BzR9KAClHWkooBB0paM0UgFpBSdTQPrmgQtHWjPOaO9MBc0Ug60A0guFLRSUDQUUfSimAtJ3oo70gFzRSUZoAWkozR+lMOgtFJR1oAXNHSkFFAC0dqQdKM0gFopB15oPWmAtA60maO1AIWj8KQUUBYX9aKQGigA9qKM0d6QCig0lFAgo60DpRQMO1ITRmk7UCEprdKcaQ0DGGoyKeaY3ftSAYSKhbpUp7d6jbmkxoiPFN7U5vu9aYeKQx38OR0pU9qb29q
This is the code for image:
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeBytes(ba);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",ba1));
This is the HTTP code for sending the image to the server:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://servername.com/uploadimage.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
If you find any more difficulties ask me or a check:
this similar tutorial for image uploading
Base64 example
In PHP header file changes :
header('Content-Type: image/jpg; charset=utf-8');
$base=$_REQUEST['image'];
Have you tried reading the raw post data in PHP? Something like
$data = $xml = file_get_contents('php://input');
Have a look at this link for more info
http://www.codediesel.com/php/reading-raw-post-data-in-php/
just download the Base64.java http://iharder.sourceforge.net/current/java/base64/ & put that file in your project & then
just replace the
String image_str = Base64.encodeToString(byte_arr, Base64.DEFAULT);
this with
String image_str = Base64.encodeBytes(byte_arr);
replace this post.setEntity(new UrlEncodedFormEntity(pairs));
with
post.setEntity(new UrlEncodedFormEntity(pairs,HTTP.UTF_8));
Also check while importing the Base64 it will import file from your package & then post to server it will post.
in your php code just change
change this
$base = $_POST["image"];
to
$base = $_REQUEST['image'];
Try sending your data as below:
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 60000); //1 min
HttpConnectionParams.setSoTimeout(httpParams, 60000); //1 min
HttpClient client = new DefaultHttpClient(httpParams);
HttpPost post = new HttpPost("http://myURL/uploadImage.php");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("image", image_str));
post.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8)); // as UTF-8
HttpResponse response = client.execute(post);
Is the HTTP-Response-Code you are getting 200?
If so, try setting these header-fields:
"Accept": "text/html"
"Accept-Language": "en"
"Content-Length": yourString.length
"Content-Type": "application/x-www-form-urlencoded"