简体   繁体   中英

How to upload and save multiple photo in database

Please help me.... I want to upload up to 5 photos and save in database. I want by selecting photo it will upload automatically and then the selected photo will appear in the page. It will occure with one by one photo, up to 5 photos and the photos can be seen in the page. Then if i submit it, it will save the photos (not the photo link) in a table named user in my database named my_db

    <?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>

And here 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;
        }
?>

There is a very good tutorial on how to do this using dropzone.js here http://www.infotuts.com/drag-drop-multiple-file-upload-with-dropzone-save-to-database/

Their php:

</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;">

Their html

<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>

My "Invoke Dropzone with some useful parameters"

var myNewDropzone = new Dropzone("#newuploadedForm",  {
//Prepare the drop zone area

    url: "<?php echo get_bloginfo('url'); ?>/path-to/your-ajax-file.php",
    method: "POST",
    uploadMultiple: true,
    autoProcessQueue: false, /* Make this true if you don't want to handle the requests in your own Javascript - much easier! */
    addRemoveLinks: false, /* Make true to let Dropzone handle remove document clicks */
    clickable: true,
    maxFiles: 10,
    parallelUploads: 10,
    maxFilesize: 50, 
    acceptedFiles:"image/png,image/gif,image/jpeg,application/pdf", /* change as needed and update the dictInvalidFileType below */
    dictInvalidFileType: "Sorry, we only support .PNG, .JPG, .GIF, and .PDF files currently",
    previewTemplate: document.querySelector('#preview-template').innerHTML, /* Remove this unless you create a preview template */
    dictMaxFilesExceeded: "Sorry, you can upload a maximum of 10 images as pages.  Please convert your images to one PDF document.",
    /* Below is a commented out example of building your own client size file handler

    init : function() {
        this.on("addedfile", function(file) { new_file_added(file); });
        //this.on("sending", function(file, xhr, formData) { sending_file(file, xhr, formData); });
        this.on("thumbnail", function(file,fileurl) { new_thumbnail_added(file); });
        this.on("removedfile", function(file) { new_file_removed(file); });
        this.on("totaluploadprogress", function(progress) { display_progress(progress); });
        this.on("queuecomplete", function() { all_files_uploaded(); });
        //this.on("processing", function(file) { new_file_processed(file); });
    } */
});

I think you will find dropzone works really well, and allows you do it the easy way (let dropzone take control) or slightly harder but you get full control of the upload process

If you want upload multiple photos to php server and save it in db. First, you should dynamic add more input file element in front page, then in your ajaximage.php, check this reserved.variables.files , got everything you need to complete your task.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM