Upload Image to MySQL blob through Android



For uploading an image to the MySQL database is really quite simple just you have to follow these simple code snippet.

Android Case
Get an image using the android you can do this by using startActivityForResult(intent,requestcode)

Use this code onClick Method of the Button
  Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
  photoPickerIntent.setType("image/*");
  startActivityForResult(photoPickerIntent, 100);

Then override this below method button in the activity

        @Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
  if(imageReturnedIntent!=null)
  {
   if(requestCode == 100){
           Uri selectedImage = imageReturnedIntent.getData();
           InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
           yourSelectedImage = BitmapFactory.decodeStream(imageStream);
           ByteArrayOutputStream stream = new ByteArrayOutputStream();
           yourSelectedImage.compress(Bitmap.CompressFormat.JPEG, 60, stream);          
           byte[] byte_arr = stream.toByteArray();
           
       }
  }
}    


Before that you have to download four  .jar file that are
1. httpclient-4.2.1.jar
2. httpcore.jar
3. httpmime-4.2.1.jar
4. mime4j-0.2.jar


After that use this code to interact with the php.

String url="http://youraddresswherephpisstored";
HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost(url);
            MultipartEntity entity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);
                    entity.addPart("image", new ByteArrayBody(EditVariable.getB(), "picture.jpg"));
                    httpPost.setEntity(entity);
                HttpResponse response = httpClient.execute(httpPost,
                        localContext);


Now the php side code :

$hostname_localhost ="yourlocalhostname";
$database_localhost ="yourdatabase";
$username_localhost ="username";
$password_localhost ="password";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);

mysql_select_db($database_localhost, $localhost); $imageName=mysql_real_escape_string($_FILES["image"]["name"]);
$imageData=mysql_real_escape_string(file_get_contents($_FILES["image"]["tmp_name"])); $imagetype=mysql_real_escape_string($_FILES["image"]["type"]);
$result = mysql_query("mysql command  theblobtypecoloumn='$imageData' ");



Now its done you got your problem solved.
       
     

Comments

Popular posts from this blog

Making Bootable Pendrive with .bat file

Ek Beej Tha Gaya Bahut Hee Gaharaee Mein Boya - Nanha Paudha

R-W-W (Real, Win, Worth it ) - Boost your idea