通过PHP将图像文件(通过表单,仅在文件夹中选择)上传到mysql?

时间:2016-05-30 04:34:34

标签: javascript php jquery html mysql

我只是不清楚如何格式化 - 过去我让用户通过表单和javascript上传他们从计算机中选择的图像:

$("#uploadimage").on('submit',(function(e) {
        e.preventDefault();


        $.ajax({
        url: "../php/upload.php", // Url to which the request is send
        type: "POST",             // Type of request to be send, called as method
        data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
        contentType: false,       // The content type used when sending data to the server.
        cache: false,             // To unable request pages to be cached
        processData:false,        // To send DOMDocument or non processed data file it is set to false
        success: function(data)   // A function to be called if request succeeds
        {

        }
        });
        }));

将文件发送到php脚本:

if(isset($_FILES["file"]["type"]))
{
$validextensions = array("jpeg", "jpg", "png");
$maxsize = 99999999;
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
) && ($_FILES["file"]["size"] < $maxsize)//Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {

$size = getimagesize($_FILES['file']['tmp_name']);
$type = $size['mime'];
$imgfp = fopen($_FILES['file']['tmp_name'], 'rb');
$size = $size[3];
$name = $_FILES['file']['name'];

$sql = new mysqli("localhost","username","password","sqlserver");
$imgfp64 = base64_encode(stream_get_contents($imgfp));
$update = "UPDATE sqlserver.imageblob set image='".$imgfp64."', image_type='".$type."', image_name='".$name."', image_size='".$size."' where user_id=".$account['id'];
$sql->query($update);

然后我就能像这样显示图像并回显HTML:

$imgdata = $array['image']; //store img src
     $src = 'data:image/jpeg;base64,'.$imgdata;

但是现在我需要将已经存储的图像文件上传到文件夹中,即../images/image1.png不是表格上传的文件。

理想情况下我会写:

$imgfile = "../images/image1.png"

然后将其插入我的php代替$_FILES['file']['name'],但我不知道如何正确地写出来。我是mysql的新手,只是传递一个像上面这样的文件名的错误消息。

如何将我文件夹中已有的图像上传到mysql表?

我尝试过:

enter image description here

1 个答案:

答案 0 :(得分:2)

您可以使用DirectoryIterator

将此文件保存到images文件夹并运行它:

<?php

    $validextensions = array("jpeg", "jpg", "png");
    $dir = new DirectoryIterator(dirname(__FILE__));
    foreach ($dir as $fileinfo) {
        if (!$fileinfo->isDot()) {

            $extension = strtolower(pathinfo($fileinfo->getFilename(), PATHINFO_EXTENSION)); /* GET EXTENSION OF FILE */

            if(in_array($extension, $validextensions)){ /* IF FILE IS IMAGE; JPEG, JPG, OR PNG */

                /* CHECK IF IMAGE IS ALREADY IN THE DATABASE */
                $check = $sql->query("SELECT * FROM image_table WHERE image_col = ?"); /* REPLACE NECESSARY TABLE AND COLUMN NAME */
                $check->bind_param("s", $fileinfo->getFilename());
                $check->execute();
                $check->store_result();
                $noofrows = $check->num_rows;
                $check->close();

                if($noofrows == 0){ /* IF IMAGE NAME IS NOT YET IN THE DATABASE */
                    /* INSERT FILE NAME TO DATABASE */
                    $stmt = $sql->query("INSERT INTO image_table (image_col) VALUES (?)"); /* REPLACE NECESSARY TABLE AND COLUMN NAME */
                    $stmt->bind_param("s", $fileinfo->getFilename());
                    $stmt->execute();
                    $stmt->close();
                }

            }
        }
    }

?>

上面会将图像名称保存到您的数据库中。

当您想要显示图像时,只需运行此查询:

$getimg = $sql->prepare("SELECT image_col FROM image_table"); /* REPLACE NECESSARY TABLE AND COLUMN NAME */
$getimg->execute();
$getimg->bind_result($image);
while($getimg->fetch()){
    echo '<img src="images/'.$image.'">';
}
$getimg->close();