【问题标题】:Multiple Image Upload PHP form with one input一个输入的多张图片上传 PHP 表单
【发布时间】:2014-07-22 18:37:15
【问题描述】:

我已经尝试了很长一段时间了。但我似乎无法让它工作。我想要一个只使用一个输入的多图像上传表单。

这是我的上传.php

<?php
include("../include/session.php");

session_start();
$allowedExts = array("jpeg", "jpg", "png", "gif");
$extension = end(explode(".", $_FILES["upload"]["name"]));

if(isset($_FILES['upload']['tmp_name']))
{
    for($i=0; $i < count($_FILES['upload']['tmp_name']);$i++)
    {

        if (($_FILES["upload"]["name"] < 90000000000000000)
            && in_array($extension, $allowedExts)) {
                if ($_FILES["upload"]["error"] > 0)
                {
                    header('location: '.$error); die;
                }
                else
                {

                    if (file_exists("../icons/".$_SESSION["username"] ."/" . $_FILES["upload"]["name"]))
                    {
                    echo "error";
                    }
                    else
                    {
                        if(!is_dir("../icons/". $_SESSION["username"] ."/")) {
                            mkdir("../icons/". $_SESSION["username"] ."/");
                        }

                        $temp = explode(".",$_FILES["upload"]["name"]);
                        $file = rand(1,999999999999) . '.' .end($temp);

                        move_uploaded_file($_FILES["upload"]["tmp_name"], "../icons/". $_SESSION["username"] ."/". $file);  
                    }
                }
            }
        } else {
            echo "yep error";
        }
    }
} 
?>

如果我把线拿出来

if(isset($_FILES['upload']['tmp_name']))
{
    for($i=0; $i < count($_FILES['upload']['tmp_name']);$i++)
    {

使用相应的右括号,它似乎工作正常。图片上传完美。但问题是,它只允许我上传一个。

我真的需要你的专业知识。谢谢

【问题讨论】:

标签: php image file-upload image-uploading multiple-file-upload


【解决方案1】:
extract($_POST);
$error=array();
$extension=array("jpeg","jpg","png","gif");
foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name) {
    $file_name=$_FILES["files"]["name"][$key];
    $file_tmp=$_FILES["files"]["tmp_name"][$key];
    $ext=pathinfo($file_name,PATHINFO_EXTENSION);

    if(in_array($ext,$extension)) {
        if(!file_exists("photo_gallery/".$txtGalleryName."/".$file_name)) {
            move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"photo_gallery/".$txtGalleryName."/".$file_name);
        }
        else {
            $filename=basename($file_name,$ext);
            $newFileName=$filename.time().".".$ext;
            move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"photo_gallery/".$txtGalleryName."/".$newFileName);
        }
    }
    else {
        array_push($error,"$file_name, ");
    }
}

你必须检查你的 HTML 代码

<form action="create_photo_gallery.php" method="post" enctype="multipart/form-data">
    <table width="100%">
        <tr>
            <td>Select Photo (one or multiple):</td>
            <td><input type="file" name="files[]" multiple/></td>
        </tr>
        <tr>
            <td colspan="2" align="center">Note: Supported image format: .jpeg, .jpg, .png, .gif</td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input type="submit" value="Create Gallery" id="selectedButton"/></td>
        </tr>
    </table>
</form>

不错的链接:

PHP Single File Uploading with vary basic explanation.

PHP file uploading with the Validation

PHP Multiple Files Upload With Validation Click here to download source code

PHP/jQuery Multiple Files Upload With The ProgressBar And Validation (Click here to download source code)

How To Upload Files In PHP And Store In MySql Database (Click here to download source code)

【讨论】:

  • 以及如何将这些图像保存到数据库?
  • @AsifMehmood 将图像作为 blob 文件保存到数据库中确实不是一个好主意,除非您正在处理一个小型且无 SEO 搜索的项目。
  • @AsifMehmood 请看这里:javascripthive.info/php/…
  • 为什么使用extract($_POST);?我删除它并且代码运行良好。而$_POST 上的extract 似乎是糟糕的编码实践。您可以在 php.net 手册php.net/manual/en/function.extract.php中找到警告“不要对不受信任的数据使用 extract(),例如用户输入(即 $_GET、$_FILES 等)” >
  • @PreciousTom 那么不将图像保存到数据库的替代方法是什么?
【解决方案2】:

使用 php 上传多张图片的完整源代码和预览可在以下链接中找到。
示例代码:

if (isset($_POST['submit'])) {
    $j = 0; //Variable for indexing uploaded image 

    $target_path = "uploads/"; //Declaring Path for uploaded images
    for ($i = 0; $i < count($_FILES['file']['name']); $i++) { //loop to get individual element from the array

        $validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed
        $ext = explode('.', basename($_FILES['file']['name'][$i])); //explode file name from dot(.) 
        $file_extension = end($ext); //store extensions in the variable

        $target_path = $target_path.md5(uniqid()).
        ".".$ext[count($ext) - 1]; //set the target path with a new name of image
        $j = $j + 1; //increment the number of uploaded images according to the files in array       

        if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded.
            && in_array($file_extension, $validextensions)) {
            if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) { //if file moved to uploads folder
                echo $j.
                ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
            } else { //if file was not moved.
                echo $j.
                ').<span id="error">please try again!.</span><br/><br/>';
            }
        } else { //if file size and file type was incorrect.
            echo $j.
            ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
        }
    }
}

http://www.allinworld99.blogspot.com/2015/05/php-multiple-file-upload.html

【讨论】:

  • 我想补充一点,初始的 $target_path 变量需要在 for 循环内,否则通过 md5 散列的文件名被连接起来。此外,我删除了散列文件名方法,因为它不适合我的需要。
【解决方案3】:
<?php
if(isset($_POST['btnSave'])){
    $j = 0; //Variable for indexing uploaded image 

    $file_name_all="";

    $target_path = "uploads/"; //Declaring Path for uploaded images

    //loop to get individual element from the array
    for ($i = 0; $i < count($_FILES['file']['name']); $i++) {

        $validextensions = array("jpeg", "jpg", "png");  //Extensions which are allowed
        $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.) 
        $file_extension = end($ext); //store extensions in the variable
        $basename=basename($_FILES['file']['name'][$i]);
        //echo"hi its base name".$basename;
        $target_path = $target_path .$basename;//set the target path with a new name of image
        $j = $j + 1;//increment the number of uploaded images according to the files in array       

        if (($_FILES["file"]["size"][$i] < (1024*1024)) //Approx. 100kb files can be uploaded.
        && in_array($file_extension, $validextensions)) {
            if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
                echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
                /***********************************************/

                $file_name_all.=$target_path."*";  
                $filepath = rtrim($file_name_all, '*');  
                //echo"<img src=".$filepath."   >";          

                /*************************************************/
            } else {//if file was not moved.
                echo $j. ').<span id="error">please try again!.</span><br/><br/>';
            }
        } else {//if file size and file type was incorrect.
            echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
        }
    }
    $qry="INSERT INTO `eb_re_about_us`(`er_abt_us_id`, `er_cli_id`, `er_cli_abt_info`, `er_cli_abt_img`) VALUES (NULL,'$b1','$b5','$filepath')";


    $res = mysql_query($qry,$conn); 
    if($res)
        echo "<br/><br/>Client contact Person Information Details Saved successfully";
        //header("location: nextaddclient.php");
        //exit();
    else
        echo "<br/><br/>Client contact Person Information Details not saved successfully";

}
?>

这里 $file_name_all$filepath 获得 1 个上传文件名 2 次?

【讨论】:

  • 这是问题的答案吗?如果是这样,请清楚说明它在多大程度上解决了这个问题。如果这本身就是一个问题,请在此处将其删除并提出一个新问题。
【解决方案4】:

PHP 代码

<?php
error_reporting(0);
session_start();
include('config.php');
//define session id
$session_id='1'; 
define ("MAX_SIZE","9000"); 
function getExtension($str)
{
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
}

//set the image extentions
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") 
{

    $uploaddir = "uploads/"; //image upload directory
    foreach ($_FILES['photos']['name'] as $name => $value)
    {

        $filename = stripslashes($_FILES['photos']['name'][$name]);
        $size=filesize($_FILES['photos']['tmp_name'][$name]);
        //get the extension of the file in a lower case format
          $ext = getExtension($filename);
          $ext = strtolower($ext);

         if(in_array($ext,$valid_formats))
         {
           if ($size < (MAX_SIZE*1024))
           {
           $image_name=time().$filename;
           echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
           $newname=$uploaddir.$image_name;

           if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname)) 
           {
           $time=time();
               //insert in database
           mysql_query("INSERT INTO user_uploads(image_name,user_id_fk,created) VALUES('$image_name','$session_id','$time')");
           }
           else
           {
            echo '<span class="imgList">You have exceeded the size limit! so moving unsuccessful! </span>';
            }

           }
           else
           {
            echo '<span class="imgList">You have exceeded the size limit!</span>';

           }

          }
          else
         { 
             echo '<span class="imgList">Unknown extension!</span>';

         }

     }
}

?>

Jquery 代码

<script>
 $(document).ready(function() { 

            $('#photoimg').die('click').live('change', function()            { 

                $("#imageform").ajaxForm({target: '#preview', 
                     beforeSubmit:function(){ 

                    console.log('ttest');
                    $("#imageloadstatus").show();
                     $("#imageloadbutton").hide();
                     }, 
                    success:function(){ 
                    console.log('test');
                     $("#imageloadstatus").hide();
                     $("#imageloadbutton").show();
                    }, 
                    error:function(){ 
                    console.log('xtest');
                     $("#imageloadstatus").hide();
                    $("#imageloadbutton").show();
                    } }).submit();


            });
        }); 
</script>

【讨论】:

    【解决方案5】:

    与其他表格一起上传多张图片 $sql1 = "INSERT INTO event(title) VALUES('$title')";

            $result1 = mysqli_query($connection,$sql1) or die(mysqli_error($connection));
            $lastid= $connection->insert_id;
            foreach ($_FILES["file"]["error"] as $key => $error) {
                if ($error == UPLOAD_ERR_OK ){
                    $name = $lastid.$_FILES['file']['name'][$key];
                    $target_dir = "photo/";
                    $sql2 = "INSERT INTO photos(image,eventid) VALUES ('".$target_dir.$name."','".$lastid."')";
                    $result2 = mysqli_query($connection,$sql2) or die(mysqli_error($connection));
                    move_uploaded_file($_FILES['file']['tmp_name'][$key],$target_dir.$name);
                }
            }
    

    以及如何获取

    $query = "SELECT * FROM event ";
    $result = mysqli_query($connection,$query) or die(mysqli_error());
    
    
      if($result->num_rows > 0) {
          while($r = mysqli_fetch_assoc($result)){
            $eventid= $r['id'];
            $sqli="select id,image from photos where eventid='".$eventid."'";
            $resulti=mysqli_query($connection,$sqli);
            $image_json_array = array();
            while($row = mysqli_fetch_assoc($resulti)){
                $image_id = $row['id'];
                $image_name = $row['image'];
                $image_json_array[] = array("id"=>$image_id,"name"=>$image_name);
            }
            $msg1[] = array ("imagelist" => $image_json_array);
    
          }
    

    在阿贾克斯 $(document).ready(function(){ $('#addCAT').validate({ rules:{name:required:true}submitHandler:function(form){var formurl = $(form).attr('action '); $.ajax({ url: formurl,type: "POST",data: new FormData(form),cache: false,processData: false,contentType: false,success: function(data) {window.location.href ="{{ url('admin/listcategory')}}";}}); } })})

    【讨论】:

      【解决方案6】:
      $total = count($_FILES['txt_gallery']['name']);
                  $filename_arr = [];
                  $filename_arr1 = [];
                  for( $i=0 ; $i < $total ; $i++ ) {
                    $tmpFilePath = $_FILES['txt_gallery']['tmp_name'][$i];
                    if ($tmpFilePath != ""){
                      $newFilePath = "../uploaded/" .date('Ymdhis').$i.$_FILES['txt_gallery']['name'][$i];
                      $newFilePath1 = date('Ymdhis').$i.$_FILES['txt_gallery']['name'][$i];
                      if(move_uploaded_file($tmpFilePath, $newFilePath)) {
                        $filename_arr[] = $newFilePath;
                        $filename_arr1[] = $newFilePath1;
      
                      }
                    }
                  }
                  $file_names = implode(',', $filename_arr1);
                  var_dump($file_names); exit;
      

      【讨论】:

        猜你喜欢
        • 2021-12-01
        • 2012-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多