当路径存储在mysql数据库中时,如何将Image上传到localhost服务器? [英] How to upload an Image onto localhost server whilst path is stored in mysql database?

查看:355
本文介绍了当路径存储在mysql数据库中时,如何将Image上传到localhost服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用这个教程

解决方案

我也有这个问题 - 我确实弄明白了。我将快速了解如何将文件上传到目录,并将路径保存到MySQL,您可以在看到初始查询后执行多个查询,这样您就可以根据需要删除和删除文件。 Goes:


picture_upload.php




 < form action =upload.phpmethod =postenctype =multipart / form-data> 
选择要上传的图片:< br>

< input type =filename =fileToUploadid =fileToUpload>< br>< br>


< input type =submitvalue =上传图片name =submit>
< / form>




upload.php




 <?php $ target_dir =ANY_DIRECTORY_YOU_LIKE / PICTURES /; 
$ target_file = $ target_dir。基名($ _ FILES [ fileToUpload] [ 名称]);
$ uploadOk = 1;
$ imageFileType = pathinfo($ target_file,PATHINFO_EXTENSION);
//检查图像文件是实际图像还是假图像
if(isset($ _ POST [submit])){
$ check = getimagesize($ _ FILES [fileToUpload ] [ tmp_name的值]);
if($ check!== false){
echoFile is a image - 。 $ check [mime]。 ;
$ uploadOk = 1;
} else {
echo文件不是图像。;
$ uploadOk = 0;
}
}
//检查文件是否已存在
if(file_exists($ target_file)){
echo抱歉,文件已经存在。;
$ uploadOk = 0;
}
//检查文件大小
if($ _FILES [fileToUpload] [size]> 1000000){
echo抱歉,你的文件太大了。;
$ uploadOk = 0;
}
//允许某些文件格式
如果($ imageFileType = JPG &放大器;!&安培; $ imageFileType = PNG &放大器;!&安培;!$ imageFileType = JPEG
&& $ imageFileType!=gif){
echo抱歉,只允许使用JPG,JPEG,PNG和GIF文件。;
$ uploadOk = 0;
}
//检查$ uploadOk是否设置为0错误
if($ uploadOk == 0){
echo抱歉,您的文件未上传。 ;
//如果一切正常,尝试上传文件
} else {
if(move_uploaded_file($ _ FILES [fileToUpload] [tmp_name],$ target_file)){
echo文件。 basename($ _FILES [fileToUpload] [name])。 已上传。;
$ pictureName =ANY_DIRECTORY_YOU_LIKE / PICTURES /。 basename($ _FILES [fileToUpload] [name]);



$ servername =localhost;
$ username =MySQL_USERNAME;
$ password =MySQL_PASSWORD;
$ dbname =MySQL_DATABASE_NAME;

//创建连接
$ conn = new mysqli($ servername,$ username,$ password,$ dbname);
//检查连接
if($ conn-> connect_error){
die(Connection failed:。$ conn-> connect_error);
}

$ sql =UPDATE TableName SET myPicture ='$ pictureName'WHERE email ='$ myEmail'AND password ='$ myPassword';
//确保告诉MySQL你要更新哪个用户,这意味着相应地设置变量$ myEmail和$ myPassword

if($ conn-> query($ sql)== = TRUE){
echo记录更新成功;
} else {
echo错误更新记录:。 $ conn->误差;
}

$ conn-> close();





}其他{
echo抱歉,上传文件时出错。;
}
}
?>

玩得开心!哦,我的数据库正在使用VarChar拍照。如果你想要有创意并想出另一种方法 - 继续。


I was using this tutorial http://www.onlinebuff.com/article_step-by-step-to-upload-an-image-and-store-in-database-using-php_40.html to build up the code I have now. I'm also quite new to php so I had problems correcting some of his errors.

I tried to store images in the database and read them from there but what I want to do with them later will not allow me to do so, well it will be very difficult to monitor. The students will upload images onto the website and I'd like to monitor what they add up so that if someone does report the image i can then take it down easily. Therefore I have decided to use the file access route

I'd like to upload the image to the server and shortly after when the path is in the database i'd like to display it in, but right now my main concern is getting the file onto the server and the image path into the database.

When I run the php Code I get the error. I don't know why either.

Here is my php Code :

    <?php
    $con = mysqli_connect('localhost', 'root', 'root', 'koleesy');
    if (mysqli_connect_errno()) // Check connection
          {   echo "Failed to connect to MySQL: " . mysqli_connect_error();  }
    $dirpath = dirname(getcwd());

        function GetImageExtension($imagetype)
         {
           if(empty($imagetype)) return false;
           switch($imagetype)
           {
               case 'image/bmp': return '.bmp';
               case 'image/gif': return '.gif';
               case 'image/jpeg': return '.jpg';
               case 'image/png': return '.png';
               default: return false;
           }
         }



if (!empty($_FILES["uploadedimage"]["name"])) {

    $file_name=$_FILES["uploadedimage"]["name"];
    $temp_name=$_FILES["uploadedimage"]["tmp_name"];
    $imgtype=$_FILES["uploadedimage"]["type"];
    $ext= GetImageExtension($imgtype);
    $imagename=date("d-m-Y")."-".time().$ext;
    $target_path = $dirpath.$imagename;


if(move_uploaded_file($temp_name, $target_path)) {

    $Imageup="INSERT into 'images_tbl' ('images_path','submission_date') VALUES 

('".$target_path."','".date("Y-m-d")."')";
    if ($con->query($Imageup) === TRUE) {
    echo "New record created successfully"; }


else{

   echo("Error While uploading image on the server");
}
}
}
?>

Here is the index file where i'm testing it. Just an upload button and choose file.

<html lang="en">
<head>
    <title>Uploading Image to Folder Test</title>
</head>
<body>
    <form action="saveimage.php" enctype="multipart/form-data" method="post">

<table style="border-collapse: collapse; font: 12px Tahoma;" border="1" cellspacing="5" cellpadding="5">
<tbody><tr>
<td>
<input name="uploadedimage" type="file">
</td>

</tr>

<tr>
<td>
<input name="Upload Now" type="submit" value="Upload Image">
</td>
</tr>


</tbody></table>

</form>
</body>
</html>

I've looked at other examples but they all look very different. They use public void and stuff. Dunno what that is.

解决方案

I also had this problem - I did figure it out though. I'll do a quick walk-through of how to upload a file to a directory, and save the path into MySQL, you can do multiple queries after you see the initial query, that way you can drop and delete the file as you wish. Here Goes:

picture_upload.php

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:<br>

    <input type="file" name="fileToUpload" id="fileToUpload"><br><br>


    <input type="submit" value="Upload Image" name="submit">
</form>

upload.php

    <?php $target_dir = "ANY_DIRECTORY_YOU_LIKE/PICTURES/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    // Check if image file is a actual image or fake image
    if(isset($_POST["submit"])) {
        $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
        if($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;
        } else {
            echo "File is not an image.";
            $uploadOk = 0;
        }
    }
    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }
    // Check file size
    if ($_FILES["fileToUpload"]["size"] > 1000000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }
    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }
    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
            $pictureName = "ANY_DIRECTORY_YOU_LIKE/PICTURES/". basename( $_FILES["fileToUpload"]["name"]);



$servername = "localhost";
$username = "MySQL_USERNAME";
$password = "MySQL_PASSWORD";
$dbname = "MySQL_DATABASE_NAME";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "UPDATE TableName SET myPicture='$pictureName' WHERE email='$myEmail' AND password='$myPassword'";
// Make Sure to tell MySQL which user you want to update which means setting the variable $myEmail and $myPassword accordingly

if ($conn->query($sql) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}

$conn->close();





    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

Have Fun! Oh, and my Database is using VarChar for pictures. If you want to get creative and figure out another way - go ahead.

这篇关于当路径存储在mysql数据库中时,如何将Image上传到localhost服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆