多个文件上传与图像预览

时间:2015-11-19 11:33:31

标签: javascript php jquery html ajax

我有一个多文件上传表格,我需要显示上传图片的实时预览。我已经通过使用jQuery实现了这一点。但是从预览图像中,我想选择默认图像(单选按钮以及要选择的图像)。

<input type="file" name="pictures[]" multiple="multiple" id="fileupload" />

<div id="dvPreview"></div>

用于显示文件预览的JQuery代码;

$("#fileupload").change(function () {
    if (typeof (FileReader) != "undefined") {
        var dvPreview = $("#dvPreview");
        dvPreview.html("");
        var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
        $($(this)[0].files).each(function () {
            var file = $(this);
            if (regex.test(file[0].name.toLowerCase())) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    var img = $("<img />");
                    img.attr("style", "width:150px; height:100px; margin-right: 10px;margin-top: 10px;");
                    img.attr("src", e.target.result);
                    dvPreview.append(img);
                }
                reader.readAsDataURL(file[0]);
            } else {
                alert(file[0].name + " is not a valid image file.");
                dvPreview.html("");
                return false;
            }
        });
    } else {
        alert("This browser does not support HTML5 FileReader.");
    }
});

但我需要放置一个单选按钮来选择默认图像。

现在我可以看到这样的帖子值;

array =>
      0 => array
         name => 'image-1.jpg'
         type => 'image/jpeg'
         tmp_name => '/opt/lampp/temp/phpoktbaw'
         error => 0
         size => 706557
      1 => array
         name => 'image-2.jpg'
         type => 'image/jpeg'
         tmp_name => '/opt/lampp/temp/phpl4rbsi'
         error => 0
         size => 1785309
      2 => array
         name => 'image-3.jpg'
         type => 'image/jpeg'
         tmp_name => '/opt/lampp/temp/phpn72EL4'
         error => 0
         size => 104845

如果可能,我需要使用所选的默认图像值向该数组添加一个变量。

3 个答案:

答案 0 :(得分:0)

试试这个......

<input type="hidden" name="active[]" value="0" class="active" />
<input type="radio" name="activeImage[]" onclick="$('.active').val(0);$(this).prev().val(1)" value="1" />

希望这会有所帮助......

答案 1 :(得分:0)

看看link。希望这会有所帮助。

修改

用于选择默认图像:

<?php
if(!empty($images_arr)){ 
    foreach($images_arr as $image_src){ ?>
        <ul>
            <li >
                <img src="<?php echo $image_src; ?>" alt="">
            </li>
        </ul>
<?php }
}
?>

在此代码中,图像标记下方应该有隐藏的单选按钮,并且在图像上单击所选图像下方的单选按钮将被选中。这可以使用javascript函数完成。将复选框值设置为图像URL。

点击图片的更改边框,以便用户知道图像被选中。

答案 2 :(得分:0)

多张图片上传&amp;使用php预览

&#13;
&#13;
<?php 
// database constants
define("DB_SERVER", "localhost");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_NAME", "demo3");
?>
?php


	// Create a database connection
	$connection = @mysql_connect(DB_SERVER,DB_USER,DB_PASS);
	if (!$connection) {
		die("database connection failed: " . mysql_error());
	}
	// Select a database to use
	$db_select = mysql_select_db(DB_NAME,$connection);
	if (!$db_select) {
		die("database selection failed: " . mysql_error());
	}
	?>

<?php
//product id enter
$product_id='phoneas';
$x=1;
if(isset($_FILES['files'])){
    $errors= array();
	foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
		$file_name = $key.$_FILES['files']['name'][$key];
		$file_size =$_FILES['files']['size'][$key];
		$file_tmp =$_FILES['files']['tmp_name'][$key];
		$file_type=$_FILES['files']['type'][$key];	
        if($file_size > 2097152){
			$errors[]='File size must be less than 2 MB';
        }		
        
        $photo_id=time()+$x;
        $x=$x+1;
        $query="INSERT INTO `photo`(`P_ID`, `PHOTO_ID`, `PHOTO_NAME`) VALUES ('$product_id','$photo_id','$file_name')";
        $desired_dir="uploads/".$product_id;
        if(empty($errors)==true){
            if(is_dir($desired_dir)==false){
                mkdir("$desired_dir", 0700);		// Create directory if it does not exist
            }
            if(is_dir("$desired_dir/".$file_name)==false){
                move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
            }else{									// rename the file if another one exist
                $new_dir="$desired_dir/".$file_name.time();
                 rename($file_tmp,$new_dir) ;				
            }
		 mysql_query($query);			
        }else{
                print_r($errors);
        }
    }
	if(empty($error)){
		echo "Success";
	}
}
?>
<html>
<body>
<style type="text/css">
.thumbimage {
    float:left;
    width:100px;
    position:relative;
    padding:5px;
}
</style>
<div id="wrapper">
<form action="" method="POST" enctype="multipart/form-data">
	<input id="imageupload"  type="file" name="files[]" multiple/>
	<input type="submit"/>
</form>
<div id="preview-image"></div>
</div>
  <script type='text/javascript' src='//code.jquery.com/jquery-1.9.1.js'></script>
  <script type="text/javascript">
 $("#imageupload").on('change', function () {
 
     var countFiles = $(this)[0].files.length;
 
     var imgPath = $(this)[0].value;
     var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
     var image_holder = $("#preview-image");
     image_holder.empty();
 
     if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
         if (typeof (FileReader) != "undefined") {
 
             for (var i = 0; i < countFiles; i++) {
 
                 var reader = new FileReader();
                 reader.onload = function (e) {
                     $("<img />", {
                         "src": e.target.result,
                             "class": "thumbimage"
                     }).appendTo(image_holder);
                 }
 
                 image_holder.show();
                 reader.readAsDataURL($(this)[0].files[i]);
             }
 
         } else {
             alert("It doesn't supports");
         }
     } else {
         alert("Select Only images");
     }
 });
 </script>
</body>
</html>
&#13;
&#13;
&#13;