【问题标题】:Multiple file upload with a loop循环上传多个文件
【发布时间】:2012-02-07 08:27:08
【问题描述】:

我目前有这个脚本,用户(使用可以上传最多七张图像的表单)可以将多张图像上传到一个文件夹并将图像名称上传到我的数据库,但没有任何成功。请帮忙。

if (isset($_POST['submit'])) { $ref_49 = $_POST['ref_49'];
    $name = $_POST['name'];
    $contact = $_POST['contact'];
    $email = $_POST['email'];
    $rent_sell = $_POST['rent_sell'];
    $heading = $_POST['heading'];
    $price = $_POST['price'];
    $limitedtextarea = $_POST['limitedtextarea'];
    $type = $_POST['type'];
    $where = $_POST['where'];
    $address = $_POST['address'];
    $bedroom = $_POST['bedroom'];
    $bathroom = $_POST['bathroom'];
    $garages = $_POST['garages'];
    $carports = $_POST['carports'];
    $granny_flat = $_POST['granny_flat'];
    $ref_99 = $_POST['ref_99'];
    $fulldesc = $_POST['full_desc'];

    if ($ref_99=="") {
    $full_ad = "yes";
    } else {
    $full_ad = "no";
    }
    $todays_date = date("Y-m-d");
     mkdir("gallery/" . $_POST["name"], 0777); 

for ($i = 0; $i < 7; $i++) 
{
    $file_name = $_FILES['uploadFile' . $i]['name'];
    // strip file_name of slashes
    $file_name = stripslashes($file_name);
    $file_name = str_replace("'", "", $file_name);
    // $copy = copy($_FILES['uploadFile'. $i]['tmp_name'], "gallery/" . $_POST["name"] . "/" . $file_name);

    if ((($_FILES['uploadFile' . $i]["type"] == "image/gif") 
      || ($_FILES['uploadFile' . $i]["type"] == "image/jpeg") 
      || ($_FILES['uploadFile' . $i]["type"] == "image/pjpeg")) 
      && ($_FILES['uploadFile' . $i]["size"] < 200000000)) 
    {
        if ($_FILES['uploadFile' . $i]["error"] > 0) 
        {
            $message = "Return Code: " . $_FILES['uploadFile' . $i]["error"] . "<br />";
        }
        else
        {
            $query = "INSERT INTO property (

                    name, contact, email, type_of_listing, rent_sell, address, prop_desc, area, price, main_image, image_1, image_2, image_3, image_4, image_5, image_6, heading, bathroom, bedroom, garages, carports, granny_flat, full_description, full_ad, 49_ref, 99_ref, listed 

                ) VALUES (

                    '{$name}', '{$contact}', '{$email}', '{$type}', '{$rent_sell}', '{$address}', '{$limitedtextarea}', '{$where}', '{$price}', '{$photo_1}', '{$photo_2}', '{$photo_3}', '{$photo_4}', '{$photo_5}', '{$photo_6}', '{$photo_7}', '{$heading}', '{$bathroom}', '{$bedroom}', '{$garages}', '{$carports}', '{$granny_flat}', '{$fulldesc}', '{$full_ad}', 'ref_49_{$ref_49}', 'ref_99_{$ref_99}', ''
                )";
            $result = mysql_query($query, $connection);

            if (file_exists("gallery/" . $_POST["name"] . "/" . $_FILES['uploadFile' . $i]["name"])) 
            {
                $message = "<h3>" . $_FILES['uploadFile' . $i]["name"] . " already exists.</h3>";
            }
            else
            {
                move_uploaded_file($_FILES['uploadFile' . $i]["tmp_name"], "gallery/" . $_POST["name"] . "/" . $_FILES['uploadFile' . $i]["name"]);
                $message = "File: " . $_FILES['uploadFile' . $i]["name"] . " uploaded.";
            }
        }
    }
    else
    {
        $message = "<h3>Invalid file or no file selected.</h3><br />• Only JPEG OR GIF allowed.<br />• Size limited may not exceed 200KB.<br /><a href = \"local_artist.php\">Return</a>";
    }
}
}

}

【问题讨论】:

  • 一个好的开始是解释问题。错误信息?什么不工作?
  • 对不起,史蒂夫,如果我上传所有七个文件,它可以正常工作,但是一旦我决定只上传一两个文件,我就会收到 $message 告诉我没有选择文件

标签: php database upload


【解决方案1】:

这里可能会出现很多问题。你有没有试过把它分解成碎片?您确定数据库正在连接吗?您确定 php 有权写入它尝试写入的目录吗?你确定那些目录存在......等等。等等

注释掉大部分代码,然后开始逐个测试所有组件,或者将内容包装在 try/catch 中,看看会产生什么错误。

[编辑] 如果问题仅在您上传

循环查看实际上传的文件数量,而不是固定数量。

假设它们都是按顺序命名的(并且从 0 开始),您可以在循环中测试您的散列 FILE 值是否存在,然后继续摄取,直到它出现 null(最好添加一个限制器以确保它不能永远持续下去)

这样的……

[编辑 2] 修改了条件以包含文件大小测试

for($i=0;  $_FILES['uploadFile' . $i] && $_FILES['uploadFile' . $i]['size'] > 0 && $i<100 ; $i++){
  try{
    //do your upload stuff here
  }catch(e){}
}

[编辑] 要修改您的页面以包含动态数量的字段,请执行以下操作:

看看这个小提琴:http://jsfiddle.net/RjcHY/2/

单击右侧的加号和减号按钮以查看其工作原理。我这样做是为了根据您的 php 期望命名文件按钮。

【讨论】:

  • 博士。 Dredel,是的,我的数据库连接正常,我编辑了代码并将整个脚本放入其中,这样你就可以看到我做了什么,就像我说的那样,当我上传所有七张图片时它工作正常,但是当我决定只上传两张或三、我的$message显示没有选择文件。
  • 哈哈,好的,谢谢,但是如果我循环到 100,那么我必须有 100 个文件上传字段吗?我尝试了您的代码,只是将 100 更改为 6,以便在我的表单中仅容纳 7 个文件上传字段,它可以工作,但我再次遇到问题,我必须填写所有上传字段,否则我会收到消息“无效文件或未选择文件",可能是 for each 循环,但不确定如何实现代码。
  • 啊...我明白了。好的 2 件事。 1)你应该修改你的页面,只向人们提供他们实际使用的文件上传字段的数量。如果他们需要,让他们单击一些 [+] 按钮以插入更多字段。在服务器上,您应该修改 if 语句以包括检查正在上传的文件是否确实有内容...我将再次编辑我的解决方案...
  • 至于 100... 不... 看看条件... 只要 $_FILES['uploadFile' + i] 为假(意味着您没有一个名为uploadFileX 在您上传的字段列表中),它会停止循环。我添加 100 限制的唯一原因是为了防止出现问题并陷入无限循环……这不太可能,但这是一个简单的预防措施,以防万一。
  • 博士。我谢谢你。你的男人。有用。感谢您的时间和精力,您真的帮助我摆脱了一块大石头。如果用户喜欢更多上传字段,我很乐意使用您对 [+] 按钮的想法来添加字段,但老实说,我不知道如何为其编写代码。
【解决方案2】:

在处理文件上传等常见任务时,编写一些库来处理这些任务并在需要的地方调用必要的函数。如果您创建一个上传器类文件,您可以简单地调用您创建的方法之一来处理文件上传。

这里我给你一个 Uploader 类

<?php

//Save file as Uploader.php
//File Uploading Class

class Uploader
{
private $destinationPath;
private $errorMessage;
private $extensions;
private $allowAll;
private $maxSize;
private $uploadName;
private $seqnence;
public $name='Uploader';
public $useTable =false;

function setDir($path){
$this->destinationPath = $path;
$this->allowAll = false;
}

function allowAllFormats(){
$this->allowAll = true;
}

function setMaxSize($sizeMB){
$this->maxSize = $sizeMB * (1024*1024);
}

function setExtensions($options){
$this->extensions = $options;
}

function setSameFileName(){
$this->sameFileName = true;
$this->sameName = true;
}
function getExtension($string){
$ext = "";
try{
$parts = explode(".",$string);
$ext = strtolower($parts[count($parts)-1]);
}catch(Exception $c){
$ext = "";
}
return $ext;
}

function setMessage($message){
$this->errorMessage = $message;
}

function getMessage(){
return $this->errorMessage;
}

function getUploadName(){
return $this->uploadName;
}
function setSequence($seq){
$this->imageSeq = $seq;
}

function getRandom(){
return strtotime(date('Y-m-d H:iConfused')).rand(1111,9999).rand(11,99).rand(111,999);
}
function sameName($true){
$this->sameName = $true;
}
function uploadFile($fileBrowse){
$result = false;
$size = $_FILES[$fileBrowse]["size"];
$name = $_FILES[$fileBrowse]["name"];
$ext = $this->getExtension($name);
if(!is_dir($this->destinationPath)){
$this->setMessage("Destination folder is not a directory ");
}else if(!is_writable($this->destinationPath)){
$this->setMessage("Destination is not writable !");
}else if(empty($name)){
$this->setMessage("File not selected ");
}else if($size>$this->maxSize){
$this->setMessage("Too large file !");
}else if($this->allowAll || (!$this->allowAll && in_array($ext,$this->extensions))){

if($this->sameName==false){
$this->uploadName = $this->imageSeq."-".substr(md5(rand(1111,9999)),0,8).$this->getRandom().rand(1111,1000).rand(99,9999).".".$ext;
}else{
$this->uploadName= $name;
}
if(move_uploaded_file($_FILES[$fileBrowse]["tmp_name"],$this->destinationPath.$this->uploadName)){
$result = true;
}else{
$this->setMessage("Upload failed , try later !");
}
}else{
$this->setMessage("Invalid file format !");
}
return $result;
}

function deleteUploaded(){
unlink($this->destinationPath.$this->uploadName);
}

}

?>

使用 Uploader.php

<?php

$uploader = new Uploader();
$uploader->setDir('uploads/images/');
$uploader->setExtensions(array('jpg','jpeg','png','gif')); //allowed extensions list//
$uploader->setMaxSize(.5); //set max file size to be allowed in MB//

if($uploader->uploadFile('txtFile')){ //txtFile is the filebrowse element name //
$image = $uploader->getUploadName(); //get uploaded file name, renames on upload//

}else{//upload failed
$uploader->getMessage(); //get upload error message
}


?> 

用于处理多张上传,例如上传 3 张图片 重复该块如下

<?php

for($i=1;$i<=3;$i++){

    $uploader->setExtensions(array('jpg','jpeg','png','gif')); //allowed extensions list//
    $uploader->setMaxSize(.5); //set max file size to be allowed in MB//
    $uploader->setSequence($i);
    if($uploader->uploadFile('txtFile'.$i)){ //txtFile is the filebrowse element name //
       $image = $uploader->getUploadName(); //get uploaded file name, renames on upload//

    }else{//upload failed
     $uploader->getMessage(); //get upload error message
    }

}

?>

在上面的例子中,文件浏览组件被命名为txtFile1,txtFile2,txtFile3 希望你能理解我的解释。

【讨论】:

  • 谢谢 Kiran 现在要尝试一下,当我使用您的代码时,我将如何在上传图像时将数据发送到数据库
  • $image = $uploader->getUploadName();这一行给你上传的文件名。即 $image 。您可以在 mysql query (insert) 中使用此变量。或将所有上传的文件名保存在一个数组中,如 $images[] = $uploader->getUploadName();遍历数组并执行插入查询
  • 嗨 Kiran,尝试了你的代码,但失败了,我不确定如何处理你的代码,对不起,我真的是一个初学者,我将文件保存为 uploader.php(单独的文件)并将在我的原始页面中添加一个包含(uploader.php)但我收到 $uploader 未定义的错误? ?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-08
  • 1970-01-01
相关资源
最近更新 更多