将图像保存在mysql数据库的文件夹和路径中

时间:2013-06-05 10:56:50

标签: php file-upload

我有一个这样的表格:

<form method="post" enctype="multipart/form-data">
 <input type="text" id="title" placeholder="Project Title"/><br />
 <input type="text" id="vurl" placeholder="If You have any video about project write your video url path here" style="width:435px;"/><br />
<textarea id="prjdesc" name="prjdesc" rows="20" cols="80" style="border-style:groove;box-shadow: 10px 10px 10px 10px #888888;"placeholder="Please describe Your Project"></textarea>

<label for="file">Filename:</label>
<input type="file" name="file" id="file" /><br>
<input type="button" name="submit" value="Submit" id="update"/>
</form>

点击提交数据存储在数据库中并使用Ajax调用显示 这是我的js代码:

$("#update").click(function(e) {
      alert("update");
      e.preventDefault();
      var ttle = $("#title").val();
      alert(ttle);
      var text = $("#prjdesc").val(); 
      var vurl = $("#vurl").val();
      var img = $("#file").val();
      alert(vurl);
      var dataString = 'param='+text+'&param1='+vurl+'&param2='+ttle+'&param3='+img;
      $.ajax({
        type:'POST',
        data:dataString,
        url:'insert.php',
        success:function(id) {
          alert(id);
          window.location ="another.php?id="+id;;
        }
      });
    });

这里我使用insert.php存储数据并使用another.php显示 但是当我来到图像部分我不明白如何将文件存储在db中的文件夹和路径中,我的意思是我有点困惑,在insert.php中集成代码

insert.php

$host="localhost";
$username="root";
$password="";
$db_name="geny";
$tbl_name="project_details";


mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

 $name = $_POST['param'];
 $video = $_POST['param1'];
 $title = $_POST['param2'];
 $sql="INSERT INTO $tbl_name (title, content, video_url) VALUES ('$title','$name','$video')";

 if(mysql_query($sql)) {
echo mysql_insert_id();

 } else {
  echo "Cannot Insert";
 }

如果我分开,那么图像存储在文件夹中..

如果我分开,那么表格代码是:

    <form action="upload_file.php" method="post"
  enctype="multipart/form-data">
    <label for="file">Filename:</label>
     <input type="file" name="file" id="file"><br>
     <input type="submit" name="submit" value="Submit">
     </form>

upload_file.php:

<?php
 $allowedExts = array("gif", "jpeg", "jpg", "png");
 $extension = end(explode(".", $_FILES["file"]["name"]));
 if ((($_FILES["file"]["type"] == "image/gif")
 || ($_FILES["file"]["type"] == "image/jpeg")
 || ($_FILES["file"]["type"] == "image/jpg")
 || ($_FILES["file"]["type"] == "image/pjpeg")
 || ($_FILES["file"]["type"] == "image/x-png")
 || ($_FILES["file"]["type"] == "image/png"))
    && ($_FILES["file"]["size"] < 50000)
    && in_array($extension, $allowedExts))
  {
 if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
 else
{
   echo "Upload: " . $_FILES["file"]["name"] . "<br>";
   echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

if (file_exists("C:/wamp/www/WebsiteTemplate4/upload/" . $_FILES["file"]["name"]))
  {
  echo $_FILES["file"]["name"] . " already exists. ";
  }
else
  {
  move_uploaded_file($_FILES["file"]["tmp_name"],
  "C:/wamp/www/WebsiteTemplate4/upload/" . $_FILES["file"]["name"]);
 // echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
  $tmp = "C:/wamp/www/WebsiteTemplate4/upload/" . $_FILES["file"]["name"];
  echo $tmp;
  }
  }
}
else
 {
 echo "Invalid file";
 }
?>

这完美地运作......

我的问题是如何在insert.php中集成此代码... 请帮帮我......

5 个答案:

答案 0 :(得分:1)

此代码可以在不使用javascript的情况下正常工作。但请确保更改“2”和“66”分别的目录和表名称和字段。

我们将创建一个隐藏的textarea,它将创建数据字符串,我们将使用$ _GET获取所有参数

<script>
$("#update").click(function(e) {
  alert("update");
  e.preventDefault();
  var ttle = $("#title").val();
  alert(ttle);
  var text = $("#prjdesc").val(); 
  var vurl = $("#vurl").val();
  var img = $("#file").val();
  alert(vurl);
  var textareastring = $('#string').val();
  var dataString = 'textareastring' = textareastring;
  $.ajax({
    type:'POST',
    data:dataString,
    url:'insert.php?param='+text+'&param1='+vurl+'&param2='+ttle+'&param3='+img',
    success:function(id) {
      alert(id);
      window.location ="another.php?id="+id;;
    }
  });
});
</script>
<textarea id="string" style="display:none;">aa</textarea>
<?php
$name = $_GET['param3']; 
// The name.n ow replacing all the $file_name with $name
$url = $_GET['param1'];
$text = $_GET['param'];
$title = $_GET['param2'];
$upload_dir = $url;
$num_files = 1;
//the file size in bytes.
$size_bytes =104857600; //51200 bytes = 50KB.
//Extensions you want files uploaded limited to.
$limitedext = array(".tif",".gif",".png",".jpeg",".jpg");
//check if the directory exists or not.
if (!is_dir("$upload_dir")) {
  die ("Error: The directory <b>($upload_dir)</b> doesn't exist.  ");
}
//check if the directory is writable.
if (!is_writeable("$upload_dir")){
  die ("Error: The directory <b>($upload_dir)</b> .  ");
}
if (isset($_POST['upload_form'])){

   echo "<h3>Upload results:</h3><br>";

   //do a loop for uploading files based on ($num_files) number of files.
   for ($i = 1; $i <= $num_files; $i++) {

       //define variables to hold the values.
       $new_file = $_FILES['file'.$i];
       $name = $new_file['name'];
       //to remove spaces from file name we have to replace it with "_".
       $name = str_replace(' ', '_', $name);
       $file_tmp = $new_file['tmp_name'];
       $file_size = $new_file['size'];

       #-----------------------------------------------------------#
       # this code will check if the files was selected or not.    #
       #-----------------------------------------------------------#

       if (!is_uploaded_file($file_tmp)) {
          //print error message and file number.
          echo "File: Not selected.<br><br>";
       }else{
             #-----------------------------------------------------------#
             # this code will check file extension                       #
             #-----------------------------------------------------------#

             $ext = strrchr($name,'.');
             if (!in_array(strtolower($ext),$limitedext)) {
                echo "File $i: ($name) Wrong file extension.  <br><br>";
             }else{
                   #-----------------------------------------------------------#
                   # this code will check file size is correct                 #
                   #-----------------------------------------------------------#

                   if ($file_size > $size_bytes){
   echo "File : ($name) Faild to upload. File must be no larger than <b>100   MB</b> in size.";
                   }else{
                #-----------------------------------------------------------#
                # this code check if file is Already EXISTS.                #
                #-----------------------------------------------------------#
                         if(file_exists($upload_dir.$name)){
                             echo "File: ($name) already exists.    <br><br>";
                         }else{
                               #-------------------------------#
                               # this function will upload the files.         #
                               #-------------------------------#
                               if     (move_uploaded_file($file_tmp,$upload_dir.$name)) {
                                   $sql = "INSERT INTO table_name(field1, field2) VALUES('$field1', '$field2');";
                                   echo "File: ($name) has been uploaded successfully." . "<img src='uploads/$name'/>";  

                               }else{
                                    echo "File: Faild to upload.  <br><br>";
                               }#end of (move_uploaded_file).

                         }#end of (file_exists).

                   }#end of (file_size).

             }#end of (limitedext).

       }#end of (!is_uploaded_file).

   }#end of (for loop).
   # print back button.
 ////////////////////////////////////////////////////////////////////////////////
 //else if the form didn't submitted then show it.
}else{
echo "<form method=\"post\" action=\"$_SERVER[PHP_SELF]\" enctype=\"multipart/form-        data\">";
       // show the file input field based on($num_files).
       for ($i = 1; $i <= $num_files; $i++) {
           echo "<b>Image: </b><input type=\"file\" size=\"70\"             name=\"file". $i ."\" style=\"width:45%\">";
       }
echo " <input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"$size_bytes\">
       <input type=\"submit\" name=\"upload_form\" value=\"Upload\">
       </form>";
}
?>

答案 1 :(得分:1)

从此链接中参考如何使用ajax上传图像。它会对你有所帮助。

http://www.9lessons.info/2011/08/ajax-image-upload-without-refreshing.html

答案 2 :(得分:0)

...您可以查看本文中提到的此代码,(http://jagdeepmalhi.blogspot.ru/2011/02/phpmysql-store-file-path-in-database.html) 它有示例代码,如果出现问题,请不要忘记阅读有关它的注释!

答案 3 :(得分:0)

如果您的意思是在单击提交按钮后如何调用insert.php,则在此行中

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

你必须添加这个

<form method="post" enctype="multipart/form-data" action="insert.php">

答案 4 :(得分:-1)

<?php

/*dont use path like this C:/wamp/www/WebsiteTemplate4/upload/ becuase you are working at localhost server*/
if (file_exists("upload/" . $_FILES["file"]["name"])){

    echo $_FILES["file"]["name"] . " already exists. ";

}else{

    $file = $_FILES["file"]["name"]
    $filePath = "upload/" . $file;
    if(move_uploaded_file($_FILES["file"]["tmp_name"], $filePath)){

        /*prepare sql query here and insert*/
        $sql = "INSERT INTO table_name(field1, field2) VALUES('$field1', '$field2');";
        if(mysql_query($sql)){

            echo "File saved in database successfully <strong>{$filePath}</strong>";

        }else{

            echo "File not uploaded there are an error <strong>{$filePath}</strong>";

        }


    }else{

        echo "File not uploaded there are an error <strong>{$file}</strong>";

    }


} ?>

如果您有任何疑问或代码无法正常工作,请尝试此代码,然后再次询问我。 感谢