繁体   English   中英

如何使用Mysqli(PHP)在Mysql中将Ajax传递的图像作为Blob插入

[英]How to insert Ajax Passed image as Blob In Mysql Using Mysqli(PHP)

我正在尝试在客户端和服务器端使用Ajax上传图像,而我正在使用PHP。 我面临的问题是,我无法使用PHP将Mysql数据库表中的图像保存为Blob。 我无法定义图像的接收功能。

我需要有关如何定义接收功能以及在数据库列中保存Blob图像的帮助。
我在下面的PHP代码中缺少某些内容吗?

Java脚本:

    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script type="text/javascript">
    $(document).ready(function (e) {
        $("#uploadForm").on('submit',(function(e) {
            e.preventDefault();
            $.ajax({
                url: "upload.php",
                type: "POST",
                data:  new FormData(this),
                contentType: false,
                cache: false,
                processData:false,
                success: function(data)
                {
                $("#targetLayer").html(data);
                },
                error: function() 
                {
                }           
           });
        }));
    });
    </script>

HTML:

    <form id="uploadForm" action="" method="post">

    <div id="uploadFormLayer">
    <label>Upload Image File:</label><br/>
    <input name="userImage" type="file" class="inputFile" />
    <input type="submit" value="Submit" class="btnSubmit" />
    </form>

PHP:

$db = mysqli_connect("xxxx","xxx","xxx","xxx"); 

$image = addslashes(is_uploaded_file($_FILES['userImage']['tmp_name']));

    $query = "INSERT INTO images (id,image) VALUES('','$image')";  

    $qry = mysqli_query($db, $query);

尝试这个...

file_get_contents()是将文件内容读取为字符串的首选方法。 如果操作系统支持,它将使用内存映射技术来提高性能。

在您的表单中添加“ enctype =“ multipart / form-data”'

<form id="uploadForm" action="" method="post" enctype="multipart/form-data">

 $query = "INSERT INTO images (id,image) VALUES('','" . mysql_escape_string(file_get_contents($image)) . "')";  
// Detect if POST
if($_SERVER["REQUEST_METHOD"] == "POST"){
  // Check $_FILES array
  if(isset($_FILES["inputFile"])){

    // Find location of uploaded file
    $tmpName = $_FILES["inputFile"]["tmp_name"];

    // Read data
    $fileHandle = fopen($tmpName, "r");
    $image = fread($fileHandle, filesize($tmpName));
    fclose($fileHandle);

    // Run query
    $db = mysqli_connect("xxxx","xxx","xxx","xxx"); 
    $query = "INSERT INTO images (id,image) VALUES('','$image')";  
    $qry = mysqli_query($db, $query);
  }
}

请记住添加有关文件大小和类型的安全性。 这是PHP文件上传文档

另外,不确定为什么将空字符串传递到表的id列中。 如果此字段具有auto_increment(例如SERIAL数据类型),则可以在SQL中将该字段保留为空白:

INSERT INTO images (image) VALUES('$image');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM