在网站上传图片,将该图片保存在我的计算机上的数据库中

时间:2013-11-24 08:58:59

标签: php xampp

我有一个网站,我上传了一些新闻。对于任何新闻我都可以上传一张图片。我想在上传图片时将img保存在某个文件夹和数据库中。我尝试了但是它没有用我做了这个

  if( $file['size'] > 0 ){
    // CHECK IS VALID FILE

    // UPLOAD THE FILE CODE HERE
    $directory_pic = LOCALPATH."Tnews\pictures".(int)($id/1000)."/";
    if(!is_dir($directory_pic))mkdir($directory_pic);

    $file_name = mysql_real_escape_string($_POST['picture']);
    if( !$file_name ) $file_name = mysql_real_escape_string($file['name']);

    // get extention
    $a = explode(".", $file['name']);
    $ext = $a[ count($a)-1 ];

    $file_name_md5 = md5(microtime());

    $new_file_path = $directory_pic.$file_name_md5.".".$ext;

    // COPY THE FILE AND INSERT IN DB
    if( copy($file['tmp_name'], $new_file_path) ){
    $file_name_ins = $file_name_md5.".".$ext;
    $imaged=$file_name_ins; 

    }

 }   

这是html输入

<h3 id="txt_i">Снимка:</h3><input type="file" accept="image/jpeg, image/png" name="picture" size="350000">

我正在使用xampp,我想将文件保存在xampp文件夹中(htdocs);

1 个答案:

答案 0 :(得分:0)

执行上传并保存在数据库中:

<form action="#" method="POST" enctype="multipart/form-data">
<table>
    <tr>
        <td>Image:</td>
        <td> <input name="poza" type="file" id="poza" ></td>
    </tr>
    <tr>
        <td>Title:</td>
        <td><input name="title" type="text" id="titlu" value=""></td>
    </tr>
    <tr>
        <td><input name="submitbutton" type="submit" value="Submit"></td>
    </tr>
</table>
</form>

和php:

class Upload extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{


if($_POST['submitbutton'])
 {

     $name = $_FILES['poza']['name'];
     $type = $_FILES['poza']['type'];
     $size = $_FILES['poza']['size'];
     $tmp =  $_FILES['poza']['tmp_name'];
     $title = $_POST['title'];
     $code='';


     $charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789";
     $lenght = 5;
     for($i=0; $i<=$lenght; $i++)
     {
         $rand = rand() % strlen($charset);
         $temp = substr($charset, $rand, 1);
         $code .= $temp; 
     }
     $query = $this->db->query("SELECT code FROM table WHERE 'code'='$code'");
     $numrows = $query->num_rows();

     while($numrows != 0)
     {
           for($i=0; $i<=$lenght; $i++)
                {
                    $rand = rand() % strlen($charset);
                    $temp = substr($charset, $rand, 1);
                    $code .= $temp; 
                    $this->smarty->assign('code', $code);
                }
        $query = $this->db->query("SELECT code FROM table WHERE 'code'='$code'");
        $numrows = $query->num_rows();

     }

     mkdir('assets/image/'.$code);
     move_uploaded_file($tmp, 'assets/image/'.$code.'/'.$name);

  $query = $this->db->query("INSERT INTO `images`(`title`, `code`, `name`, `size`) 
             VALUES ('$title', '$code', '$name', '$size')");


 }
 else
 {   die();   
    //echo "No file selected"; 
 }

}
}