【问题标题】:How to save an image file (BLOB) in the database using jquery, ajax and php如何使用 jquery、ajax 和 php 在数据库中保存图像文件 (BLOB)
【发布时间】:2019-09-15 15:26:29
【问题描述】:

我想使用 jquery、Ajax 和 PHP 将我的数据库中的图像保存为 BLOB 文件。 我可以上传它并在表单中显示它(如果它是手动插入到数据库中的)。但是,当我在表单上更改它时,新图像会很好地显示,但是当我单击保存时,它不会保存在数据库中。我在这里没有找到任何使用 jquery、Ajax 和 PHP 的解决方案,并将整个图像存储在数据库中。

这是我的 HTML 代码(Content/users.php)的一部分:

   <img src="images/defaultprofile.png" id="photoUserUpload"
   name="image" onClick="triggerClick()" />
   <input type="file"name="profileImage" id="profileImage" style="display: 
   none;" accept=".jpg, .png" onchange="displayImage(this)" />
</div>
<div> 
  <button id="saveTechItem" class="btn btn-primary saveTechItem">Save</button></div> 

这是我的 js 代码的一部分(Data_Scripts/users.js):

$(document).on("click", ".saveItem", function() {
    if (validateForm()) {   
        addOrUpdateItem();
    }
});
function addOrUpdateItem(event) {
    var itemId = $("#userId").val();
    var fullName = $("#txtUserName").val();

    var pic=$("#photoUserUpload").attr('src');
    alert (pic);

    //I tried also to append the file before submit
    var file=new FormData();
    file.append('file', file2);
    //alert (file2);

    var itemData = {
        id: itemId,
        postType: 'addOrUpdate',
        fullName: fullName,
        pic:pic
    };

    $.ajax({
        url: 'data_ajax/users.php',
        data: itemData,
        type: "POST",
        cache: false,
        success: function(data) {
               location.reload();
        },
        error: function(e) {
            alert("error while trying to add or update user!");
        }
    });   
}

这是我的一部分 PHP 代码(DataAjax/user.php):

if (isset($_POST['id'])) {
    $postType = $_POST['postType'];
    if ($postType == "addOrUpdate") {   
        $Id = $_POST['id'];
        $FullName = $_POST['userName']; 
        $pic = base64_encode(file_get_contents($_POST['pic']));
        $data = new Data();
        $db = $data->dataHandler();
        $query = "INSERT INTO Users (`id`, `fullname`, `image`) 
                values ('$Id', '$FullName', '$pic')";
        $db->query($query);
         }
}

【问题讨论】:

    标签: php jquery html ajax


    【解决方案1】:

    您在 postdata 中以错误的方式传递图像数据,请尝试以下代码中的示例

    html文件输入:

    <input type="file"name="profileImage" id="profileImage" accept=".jpg, .png"  />
    

    带有AJAX代码的脚本文件代码:

    var itemId = $("#userId").val();
        var fullName = $("#txtUserName").val();
        var filedata = $("#profileImage").val();
    
        //Your Formdata Ready To Send
        var data = new FormData();
        data.append('file', filedata);
        data.append('id', itemId);
        data.append('fullName', fullName);
    
    
    $.ajax({
        url: 'data_ajax/users.php',
        data: data,
        type: "POST",
        contentType: false,
        cache: false,
        processData:false,
        success: function(data) {
               location.reload();
        },
        error: function(e) {
            alert("error while trying to add or update user!");
        }
    }); 
    

    PHP 文件代码:

    if (isset($_POST['id'])) {
        $postType = $_POST['postType'];
        if ($postType == "addOrUpdate") {   
            $Id = $_POST['id'];
            $FullName = $_POST['fullName']; 
    
            // chnage this line
            $pic = base64_encode(file_get_contents($_FILES['file']));
            // or you can send all data in serilize way in database like this
            $pic = serialize($_FILES['file']);
    
            $data = new Data();
            $db = $data->dataHandler();
            $query = "INSERT INTO Users (`id`, `fullname`, `image`) 
                    values ('$Id', '$FullName', '$pic')";
            $db->query($query);
             }
    }
    

    【讨论】:

    • 我没有收到错误。 “保存”按钮起作用,它将数据提交到数据库,只有图像字段为空。我完全尝试了你的代码,它不起作用。另一方面,鉴于我不想使用 data.append('file', filedata); ,我尝试了另一种解决方案。所以,我保留了 `var itemData = { id: itemId, postType: 'addOrUpdate', fullName: fullName, pic:pic };` 其中 pic 是 var pic = $("#profileImage").val(); 并且在 PHP 代码中:$d1= $_POST['pic']; $d2=$_FILES [$d1]; $pic = base64_encode(file_get_contents($d2));
    • 再试一次,我确实改变了答案
    • 请使用:new formdata() and data.append('file', filedata);没有它就没有工作!
    • “filedata”的值为“C:\fakepath\image_name.png”。 “filedata”的值应该是图像的路径吗?为什么它是“假路径”?
    • 尝试添加:[ $pic= base64_encode(file_get_contents($_FILES['file']['tmp_name'])); $data = mysql_real_escape_string($pic); ]可能是你得到图像的真实数据
    【解决方案2】:

    要通过 ajax 上传文件,您必须使用 formdata 对象(其中包含文件/blob 对象),将其作为数据参数传递给 $.ajax 并将 processData 和 contentType 设置为 false。

    function addOrUpdateItem(event) {
        var itemId = $("#userId").val();
        var fullName = $("#txtUserName").val();
        var pic = $("#profileImage").prop('files')[0];
    
        var data = new FormData();
        data.append('id', itemId);
        data.append('postType', addOrUpdate);
        data.append('fullName', fullName);
        data.append('pic', pic);
    
        $.ajax({
            url: 'data_ajax/users.php',
            data: data,
            type: "POST",
            cache: false,
            contentType: false,
            dataType: false,
            success: function(data) {
                   location.reload();
            },
            error: function(e) {
                alert("error while trying to add or update user!");
            }
        });   
    }
    

    您必须使用$_FILES['pic'][tmp_name] 访问该文件

    if (isset($_POST['id'])) {
        $postType = $_POST['postType'];
        if ($postType == "addOrUpdate") {   
            $Id = $_POST['id'];
            $FullName = $_POST['userName']; 
            $pic = base64_encode(file_get_contents($_FILES['pic'][tmp_name]));
            $data = new Data();
            $db = $data->dataHandler();
            $query = "INSERT INTO Users (`id`, `fullname`, `image`) 
                    values ('$Id', '$FullName', '$pic')";
            $db->query($query);
             }
    }
    

    【讨论】:

    • 非常感谢。现在可以了。代替“base64_encode”,我使用了addlashes。您的代码中有一个小错误:data.append 不是 file.append。感谢您的澄清。
    猜你喜欢
    • 2015-06-19
    • 2016-11-04
    • 2014-12-11
    • 2015-05-06
    • 2011-09-10
    • 2012-04-28
    • 2015-11-15
    • 1970-01-01
    • 2018-11-08
    相关资源
    最近更新 更多