【问题标题】:upload image using javascript and xajax to MySql Blob使用 javascript 和 xajax 将图像上传到 MySql Blob
【发布时间】:2017-04-26 21:17:33
【问题描述】:

我想上传图片到数据库,但我不知道如何接收这个文件。

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

【问题讨论】:

  • 我不知道我是否将图像正确发送到 php xajax。
  • 不,这不是办法,YO需要发送文件而不是输入的值。查看更多 stackoverflow.com/questions/4856917/… 通过此链接阅读每一篇文章,cmets。
  • 感谢您的评论。我会读的。
  • php 因为我需要在那里接收文件。也许我错了。
  • 用 ajax 发送表单数据,然后在 php 中获取 $_FILES 转换为 base64 并作为 blob 保存在 mysql 数据库中。

标签: xajax


【解决方案1】:

您可以这样做: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...
        })
    }
});

代码 sn-p 示例:

<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 是否与 MySql 中的 blob 兼容?
  • CHAR/VARCHAR、BINARY、VARBINARY、BLOB都可以用来保存base64。
  • 谢谢,我去试试。
  • 我忘了粘贴一些代码,它已更新。请参阅 $("#image") 上面的代码,您需要它。我测试了代码,它对我有用 ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js
  • @LuisPavez,它有用吗?您可能无法将 base64 保存为 BLOB,因为它实际上不仅仅是 base64 数据。这是图片的base64 url​​。如果无法存储,请使用 CHAR、VARCHAR、TEXT、MEDIUMTEXT 或 LONGTEXT 将其存储在数据库中或运行正则表达式以仅获取 base64 数据并另存为 BLOB。
【解决方案2】:

在你的模板中(聪明)

<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 类 | 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);
}
?>

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

【讨论】:

    猜你喜欢
    • 2020-10-10
    • 2016-05-26
    • 2014-07-22
    • 2013-11-25
    • 2017-01-06
    • 2011-11-01
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    相关资源
    最近更新 更多