如何在数据库中上传和保存多张照片

时间:2015-08-28 05:01:17

标签: php ajax

请帮帮我.... 我想上传最多5张照片并保存在数据库中。 我想通过选择照片自动上传,然后所选照片将出现在页面中。 它会随着一张照片一起出现,最多可以拍摄5张照片,并且可以在页面中看到照片。 然后,如果我提交它,它会将照片(不是照片链接)保存在名为my_db的数据库中名为user的表中

    <?php
include('dbcon.php');
session_start();
$session_id='1'; //$session id
?>
<html>
<head>
<title>Ajax Image Upload 9lessons blog</title>
</head>
<script type="text/javascript" src="scripts/jquery.min.js"></script>
<script type="text/javascript" src="scripts/jquery.wallform.js"></script>
<script type="text/javascript" >
 $(document).ready(function() { 
            $('#photoimg').die('click').live('change', function()           { 
                       //$("#preview").html('');
                $("#imageform").ajaxForm({target: '#preview', 
                     beforeSubmit:function(){ 
                    console.log('v');
                    $("#imageloadstatus").show();
                     $("#imageloadbutton").hide();
                     }, 
                    success:function(){ 
                    console.log('z');
                     $("#imageloadstatus").hide();
                     $("#imageloadbutton").show();
                    }, 
                    error:function(){ 
                            console.log('d');
                     $("#imageloadstatus").hide();
                    $("#imageloadbutton").show();
                    } }).submit();
            });
        }); 
</script>
<style>
body
{
font-family:arial;
}
.preview
{
width:200px;
border:solid 1px #dedede;
padding:10px;
}
#preview
{
color:#cc0000;
font-size:12px
}
</style>
<body>
<div style="width:600px">
    <div id='preview'>
    </div>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload your image 
<div id='imageloadstatus' style='display:none'><img src="loader.gif" alt="Uploading...."/></div>
<div id='imageloadbutton'>
<input type="file" name="photoimg" id="photoimg" />
</div>
</form>
</div>
</body>
</html>

这里是ajaximage.php

    <?php
include('dbcon.php');
session_start();
$session_id='1'; //$session id
$path = "uploads/";
function getExtension($str) 
{
         $i = strrpos($str,".");
         if (!$i) { return ""; } 
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
 }
    $valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
    if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
        {
            $name = $_FILES['photoimg']['name'];
            $size = $_FILES['photoimg']['size'];
            if(strlen($name))
                {
                     $ext = getExtension($name);
                    if(in_array($ext,$valid_formats))
                    {
                    if($size<(1024*1024))
                        {
                            $actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
                            $tmp = $_FILES['photoimg']['tmp_name'];
                            if(move_uploaded_file($tmp, $path.$actual_image_name))
                                {
                                $sql="INSERT INTO user (image, uid)
                                VALUES
                                    ('$actual_image_name','$session_id')";
                                    echo "<img src='uploads/".$actual_image_name."'  class='preview'>";
                                }
                            else
                                echo "Fail upload folder with read access.";
                        }
                        else
                        echo "Image file size max 1 MB";                    
                        }
                        else
                        echo "Invalid file format..";   
                }
            else
                echo "Please select image..!";
            exit;
        }
?>

2 个答案:

答案 0 :(得分:0)

在这里使用dropzone.js有一个非常好的教程如何使用dropzone.js http://www.infotuts.com/drag-drop-multiple-file-upload-with-dropzone-save-to-database/

他们的php:

Python

他们的HTML

</p>
<?php
include 'db.php';
$upload_dir = 'myuploads';
 function insert_data($ar){
$obj=new DB();
$key="(f_name , f_size, f_link,f_type,d_date)";
$val="('{$ar['fname']}', '{$ar['fsize']}','{$ar['flink']}','{$ar['ftype']}','{$ar['fdate']}')";
mysqli_query($obj->connection(),"INSERT INTO file_upload ".$key." VALUES ".$val);
//mysqli_close($obj->con);
}
if (!empty($_FILES)) {
 $tempFile = $_FILES['file']['tmp_name'];
 // using DIRECTORY_SEPARATOR constant is a good practice, it makes your code portable.
 $targetPath = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . $upload_dir . DIRECTORY_SEPARATOR;
 // Adding timestamp with image's name so that files with same name can be uploaded easily.
 $fname = $targetPath.time().'-'. $_FILES['file']['name'];
 $file_name=time().'-'. $_FILES['file']['name'];
 $ftype=$_FILES["file"]["type"];
 $fsize=($_FILES["file"]["size"] / 1024);
 $tmpname=$_FILES["file"]["tmp_name"];
 // Change $flink path to your folder where you want to upload images.
 $flink='http://localhost/dragdrop%20file%20upload/myuploads/'.$file_name;
$arr= array('fname'=>$file_name,
 'fsize'=>$fsize,
 'flink'=>$flink,
 'ftype'=>$ftype,
 'fdate'=>date('Y-m-d h:i:s'));
insert_data($arr);
 move_uploaded_file($tempFile,$fname);

}
?>
<p style="text-align: justify;">

我的“使用一些有用的参数调用Dropzone”

<head>
<script src="./path/to/dropzone.js"></script>
</head>
<body>
 <div id="main">
 <p> Drag n Drop Your image files below - <b>InfoTuts</b></p>
 </div>
<form action="file-upload.php" class="dropzone"></form>
</body>

我认为你会发现dropzone工作得很好,并允许你以简单的方式(让dropzone控制)或稍微努力,但你可以完全控制上传过程

答案 1 :(得分:0)

如果您想将多张照片上传到php服务器并将其保存在db中。 首先,你应该在首页动态添加更多的输入文件元素,然后在你的ajaximage.php中,检查这个reserved.variables.files,获得完成任务所需的一切。