2017-04-26 36 views
0

我想上傳圖像到數據庫,但我不知道如何接收此文件。上傳圖像使用javascript和xajax到MySql Blob

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

我不知道我是否正確發送圖像到php xajax。 –

+0

不,這是不是的方式,你需要發送文件不是輸入的值。見更多http://stackoverflow.com/questions/4856917/jquery-upload-progress-and-ajax-file-upload/4943774#4943774通過此鏈接並閱讀每一個帖子,評論。 – webDev

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

代碼片斷例如:

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

+0

Base64與MySql中的blob兼容? –

+0

CHAR/VARCHAR,BINARY,VARBINARY和BLOB都可用於保存base64。 –

+0

謝謝,我要試一試。 –

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

FileDrop JavaScript classes |通過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); 
} 
?> 

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