2017-03-20 115 views
1

我有一個HTML表單+ PHP腳本來上傳保存原始名稱的單個圖像。我想將此腳本從單個轉換爲多個圖像上傳,並保留每個圖像的原始名稱。如何將單個PHP上傳圖像轉換爲多個上傳圖像

這是我的HTML代碼:

<form action="upload.php" method="post" enctype="multipart/form-data"> 
    <input type="file" name="userfile"/> 
    <input type="text" name="imgdec"> 
    <button name="upload" type="submit" value="Submit"> 
</form> 

這是我的PHP代碼:

<?php 


if(isset($_POST['upload'])) { 

$allowed_filetypes = array('.jpg','.jpeg','.png','.gif'); 
$max_filesize = 10485760; 
$upload_path = 'uploads/'; 
$description = $_POST['imgdesc']; 

$filename = $_FILES['userfile']['name']; 
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); 

if(!in_array($ext,$allowed_filetypes)) 
    die('The file you attempted to upload is not allowed.'); 

if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize) 
    die('The file you attempted to upload is too large.'); 

if(!is_writable($upload_path)) 
    die('You cannot upload to the specified directory, please CHMOD it to 777.'); 

if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename)) { 
    $query = "INSERT INTO uploads (name, description) VALUES ($filename, $description)"; 
    mysql_query($query); 

echo 'Your file upload was successful!'; 


} else { 
    echo 'There was an error during the file upload. Please try again.'; 
} 
} 


?> 
+0

回答

1

我知道這是一個老的文章,但一些進一步的解釋可能是有人試圖上傳多個有用文件...這裏是你需要做的:

  • 輸入名稱必須被定義爲一個數組,即name =「inputName []」
  • 輸入元素必須有多個= 「多」 或只是多
  • 在你的PHP文件中使用的語法 「$ _FILES [ 'inputName'] [ 'PARAM'] [指數]」
  • 一定要看看空文件名和路徑,該陣列可能
    包含空字符串

這裏向下和骯髒的例子(只顯示相關代碼)

HTML:

<input name="upload[]" type="file" multiple="multiple" /> 

PHP:

// Count # of uploaded files in array 
$total = count($_FILES['upload']['name']); 

// Loop through each file 
for($i=0; $i<$total; $i++) { 
    //Get the temp file path 
    $tmpFilePath = $_FILES['upload']['tmp_name'][$i]; 

    //Make sure we have a filepath 
    if ($tmpFilePath != ""){ 
    //Setup our new file path 
    $newFilePath = "./uploadFiles/" . $_FILES['upload']['name'][$i]; 

    //Upload the file into the temp dir 
    if(move_uploaded_file($tmpFilePath, $newFilePath)) { 

     //Handle other code here 

    } 
    } 
} 

希望這有助於出去!