0

I want to upload images to database, but I dont know how to receive this file.

//html
<input type="text" id="txtName">
<input type="file" id="image" onchange="sendImage()">

//Javascript
function sendImage()
{
var name = $('#txtName').val();
var image = $('#image').val(); //is this the way to send the image?
xajax_SaveImage(name, image);
}

//xajax
//with string I dont have problems for receive, but how receive I the image?
function SaveImage($name, $image)
{
   //How here I convert the image to binary for to save in Mysql
}
Luis Pavez
  • 43
  • 1
  • 2
  • 11
  • I dont know if i'm sending correctly the image to php xajax . – Luis Pavez Apr 26 '17 at 21:22
  • No this is not the way, YO need to send the file not the value of the input. see more http://stackoverflow.com/questions/4856917/jquery-upload-progress-and-ajax-file-upload/4943774#4943774 go through this link and read each and every post, comments. – BetaDev Apr 26 '17 at 21:23
  • Thanks for comment. I'll read it. – Luis Pavez Apr 26 '17 at 21:38
  • php because I need to receive the file there. Maybe I was wrong. – Luis Pavez Apr 26 '17 at 21:39
  • Send form data with ajax then in php get $_FILES convert to base64 and save in mysql database as blob. –  Apr 26 '17 at 21:44

2 Answers2

1

You can do this: base64 is the image data, upload that data to database

File.prototype.convertToBase64 = function(callback){
    var reader = new FileReader();
    reader.onload = function(e) {
        callback(e.target.result)
    };
    reader.onerror = function(e) {
        callback(null, e);
    };        
    reader.readAsDataURL(this);
};

$("#image").on('change',function(){
    var selectedFile = this.files[0];
    if (!selectedFile.name.match(/.(jpg|jpeg|png|gif)$/i)) {
    }
    else {
        selectedFile.convertToBase64(function(base64){
        //base64 is the base64 value of the image, use this to send to database...
        })
    }
});

Code snippet example:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="image">
<script>
File.prototype.convertToBase64 = function(callback){
    var reader = new FileReader();
    reader.onload = function(e) {
        callback(e.target.result)
    };
    reader.onerror = function(e) {
        callback(null, e);
    };        
    reader.readAsDataURL(this);
};

$("#image").on('change',function(){
    var selectedFile = this.files[0];
    if (!selectedFile.name.match(/.(jpg|jpeg|png|gif)$/i)) {
    }
    else {
        selectedFile.convertToBase64(function(base64){
            console.log(base64);
        })
    }
});
</script>
  • Base64 is compatible with blob in MySql ? – Luis Pavez Apr 26 '17 at 21:29
  • CHAR/VARCHAR, BINARY, VARBINARY, and BLOB can all be used to save base64. –  Apr 26 '17 at 21:30
  • Thanks, I'm going to try it. – Luis Pavez Apr 26 '17 at 21:32
  • I forgot to paste in some code, it's updated. See the code above $("#image"), you need that. I tested the code and it worked for me with https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js –  Apr 26 '17 at 21:37
  • @LuisPavez, did it work? You might not be able to save the base64 as BLOB because it's actually not only base64 data. It's the base64 url for the image. If you can't store it use CHAR, VARCHAR, TEXT, MEDIUMTEXT or LONGTEXT to store it in database or run a regular expression to only get the base64 data and save as BLOB. –  Apr 26 '17 at 22:09
0

In your template (smarty)

<div id="imageplaceholder" class="left shadow"><p>Place<br />Image<br />here.<br />(drag&amp;drop)</p></div>
<div id="image">
<div id="imageborder" class="left shadow">{if $persondata.imagesize gt 0}<img src="getimage.php?h={$smarty.session.verify}&id={$persondata.id}" />{/if}</div>
</div><div id="imagetools" class="left">
    <div id="imagehelp" class="imagetool help radius3 shadow"></div>
    <div id="imagenew" class="imagetool new radius3 shadow"></div>
    <div id="imagezoomin" class="imagetool zoomin radius3 shadow"></div>
    <div id="imagezoomout" class="imagetool zoomout radius3 shadow"></div>
    <div id="imageok" class="imagetool ok radius3 shadow"></div>
</div>

js part uses filedrop.

FileDrop JavaScript classes | by Proger_XP https://github.com/ProgerXP/FileDrop

$('#imageplaceholder').filedrop({
            // The name of the $_FILES entry:
            paramname:'pic',

            url: '/img_file.php', //this is the PHP file used for processing

            allowedfiletypes: ['image/jpeg','image/png','image/gif'],

            uploadFinished:function(i,file,response){
              // remove placeholder
              // add Image
            //  $.data(file).addClass('done');
                // response is the JSON object that img_file.php returns
                $('#imageplaceholder').hide();
                loadImage(file);
                $('#image').show();
                $('#imagetools .help').show();
                $('#imagetools .zoomin').show();
                $('#imagetools .zoomout').show();
                $('#imagetools .ok').show();

                $('#imagetools .ok').click(function(){
                    var img = $('#imageborder').find('img');
                    var offset = img.offset();
                    var pos = $('#imageborder').position();
                    offset.top = pos.top - offset.top;
                    offset.left = pos.left - offset.left;
                    var name = $('#imageborder').attr('name');
                    var scale = $('#imageborder').attr('scale');
                    var id = $('input[name=user_id]').val();
                    var hash = $('#hash').val();
                    var ret = xajax_settings_action({ xjxfun: 'settings_action' }, { parameters: ['saveimage',hash,id,name,offset,scale] }, { mode: 'synchronous' });
                    if(ret != 0)
                    {
                        $('#imagetools .help').hide();
                        $('#imagetools .zoomin').hide();
                        $('#imagetools .zoomout').hide();
                        $('#imagetools .ok').hide();
                        $('#imagetools .cancel').removeClass('cancel').addClass('new');
                    }
            });
       },
       rename: function(name) {
                // name in string format
                // must return alternate name as string
                var date = new Date();
                // get file type
                var typ = name.split('.',2);
                // buffer name for save response
                $('#imageborder').attr('name',date.getTime() + "." + typ[1]);
                return date.getTime() + "." + typ[1];
            },

            // Called before each upload is started
            beforeEach: function(file){
                if(!file.type.match(/^image\//)){
                    jAlert('Only images are allowed!');

                    // Returning false will cause the
                    // file to be rejected
                    return false;
                }
            },
        });

img_file.php

<?php

// Set the directory where files will be saved
$upload_dir = '/tmp/';
$allowed_ext = array('jpg','jpeg','png','gif');


if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
    exit_status('Error! Wrong HTTP method!');
}

if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){

    $pic = $_FILES['pic'];

        if(!in_array(get_extension($pic['name']),$allowed_ext)){
        exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
    }   

    // Move the uploaded file from the temporary 
    // directory to the uploads folder:

    if( move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name']) ){
        exit_status('File was uploaded successfuly!');
    }
}

exit_status('Something went wrong with your upload!');

// Helper functions

function exit_status($str){
    echo json_encode(array('status'=>$str));
    exit;
}

function get_extension($file_name){
    $ext = explode('.', $file_name);
    $ext = array_pop($ext);
    return strtolower($ext);
}
?>

I use simpleimage.php from Simon Jarvis to scale and crop the image.

private function save_FileDB($id,$name,$pos,$scale)
{
    $upload_dir = "/tmp/";
    $response = new xajaxResponse();
    $userid = $_SESSION['userid'];
    $binFile = $upload_dir.$name;
    if (isset($binFile) && $binFile != "none") {

        $simage = new SimpleImage();
        $simage->load($binFile);
        $simage->scale($scale*100);
        $simage->crop($pos[left],$pos[top],175,200);
        $simage->save($binFile);

        $binFile_size = filesize($binFile);
        $ext = explode('.', $name);
        $ext = strtolower( array_pop($ext) );
        switch($ext){
            case 'jpg': $binFile_type = 'image/jpeg'; break;
            case 'png': $binFile_type = 'image/png'; break;
            case 'gif': $binFile_type = 'image/gif'; break;
        }
        $data = addslashes(fread(fopen($binFile, "r"), $binFile_size ));
        $qs = "update persondata set image='$data', imagetype='$binFile_type', imagesize='$binFile_size' where id=$id";
        $ret = $this->exec_query($qs);
        unlink($binFile);
        $response->setReturnValue("1");
        return $response;
    }
    $response->setReturnValue("0");
    return $response;
}
nevtag
  • 314
  • 1
  • 6