2017-03-20 113 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 

    } 
    } 
} 

希望这有助于出去!