2012-02-07 46 views
-2

目前,我有這個腳本,用戶(使用一種形式,他們可以上傳多達七個圖像)可以上傳多張圖片到一個文件夾和圖像的名字我的數據庫中,沒有任何成功。請幫忙。多文件上傳與循環

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

} 
+3

一個好的開始就是解釋這個問題。錯誤訊息?什麼不起作用? – Steve 2012-02-07 08:30:49

+0

對不起,如果我上傳所有的七個文件,它會正常工作,但只要我決定只上傳一個或兩個文件,我就會收到$消息,告訴我沒有選擇任何文件 – user1002749 2012-02-09 13:15:50

回答

0

這裏可能會出現很多問題。你有沒有試圖把它分解成碎片?你確定數據庫連接嗎?你確定php有權寫入它試圖寫入的目錄嗎?你確定那些目錄存在...等等。等

註釋掉絕大多數的代碼,並開始測試全部由一塊一塊的部件,或包裹在try/catch語句的東西,看看產生了什麼錯誤。

如果只有當您上傳< 7個文件時纔會出現問題,那麼問題在於您已將硬編碼到您的循環中!

循環播放實際上傳的文件數量,不是固定的數字。

假設它們都是按順序命名的(並且從0開始),你可以測試循環中散列FILE值的存在性,並繼續攝取,直到它變爲空(可能是添加限制器來製作肯定不能一直持續下去)

這樣的事情...

[編輯2]修改的條件,包括對文件大小的測試

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

[編輯] 要修改您的頁面以包含動態編號場的R請勿這一點:

檢查出這個小提琴:http://jsfiddle.net/RjcHY/2/

點擊加號和減號按鈕在右側,看看它是如何工作的。我這樣做是爲了按照你的php的期望命名文件按鈕。

+0

Dr.Dredel,是的,我的數據庫連接正常,我編輯了代碼,並把整個腳本放在裏面,這樣你就可以看到我做了什麼,就像我說的,當我上傳全部7張圖片時它工作正常,但是當我決定只上傳兩張或三,我的$信息顯示沒有選擇文件。 – user1002749 2012-02-09 13:20:43

+0

編輯爲你增加的樂趣:) – 2012-02-09 16:51:59

+0

哈哈,好的謝謝,但如果我循環到100,那麼我必須有一個100文件上傳字段?我試過你的代碼只是將100更改爲6,以便在我的表單中只有7個文件上傳字段的accomadate,它的工作原理,但我坐在問題中,我必須填寫所有上傳字段,否則我會收到消息「Invalid file or no file selected 「,也許是每個循環,但不確定如何實現代碼。 – user1002749 2012-02-10 11:01:13

0

在處理像文件上傳共同任務,寫一些庫來處理這些任務和需要的地方調用必要的功能。如果您創建上傳器類文件,則可以簡單地調用您創建的用於處理文件上傳的方法之一。

在這裏,我會給你一個上傳類

<?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,txtFil e2,txtFile3 希望你能理解我的解釋。

+0

謝謝Kiran現在要嘗試它,當我使用您的代碼我要如何將數據發送到數據庫,而上傳圖片 – user1002749 2012-02-09 13:17:48

+0

$ image = $ uploader-> getUploadName();這一行給你上傳的文件名。即$圖像。你可以在mysql查詢(插入)中使用這個變量。或將所有上傳的文件名保存在一個數組中,如$ images [] = $ uploader-> getUploadName();循環訪問數組並執行插入查詢 – Kiran 2012-02-09 13:39:33

+0

嗨Kiran,嘗試了你的代碼,但是失敗了,我不確定如何處理你的代碼,抱歉我真的是初學者,我把文件保存爲uploader.php(單獨文件),並把在我的原始頁面中,你的評論「在處理多個上傳,前3個圖像上傳重複塊如下....」的代碼,並添加一個包含(uploader.php),但我得到$ uploader是未定義的錯誤? ?? – user1002749 2012-02-10 11:05:15