使用javascript和xajax将图像上传到MySql Blob

时间:2017-04-26 21:17:33

标签: xajax

我想将图像上传到数据库,但我不知道如何接收此文件。

//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
}

2 个答案:

答案 0 :(得分:0)

您可以这样做:base64是图像数据,将该数据上传到数据库

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...
        })
    }
});

代码段示例:

&#13;
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

在你的模板中(聪明)

<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使用filedrop。

FileDrop JavaScript类|通过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);
}
?>

我使用Simon Jarvis的simpleimage.php来缩放和裁剪图像。

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;
}