首页 > 解决方案 > 在上传时重命名多个图像

问题描述

我正在尝试在上传时重命名多个图像。我可以将它们上传并保存到一个文件夹中,但我似乎无法重命名它们。在我的代码和我尝试过的下面:

$targetDir = "uploads/";
$allowTypes = array('jpg','png','jpeg','gif');

$statusMsg = $errorMsg = $insertValuesSQL = $errorUpload = $errorUploadType = '';
if(!empty(array_filter($_FILES['files']['name']))){
    foreach($_FILES['files']['name'] as $key=>$val){

        $fileName = basename($_FILES['files']['name'][$key]);
        $targetFilePath = $targetDir . $fileName;

        $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
        if(in_array($fileType, $allowTypes)){
            move_uploaded_file($_FILES["files"]["tmp_name"][$key],"uploads/".$fileName.time());
            //move_uploaded_file($_FILES["files"]["tmp_name"][$key], $targetFilePath);
        }else{
            $errorUploadType .= $_FILES['files']['name'][$key].', ';
        }
    }

}else{
    $statusMsg = 'Please select a file to upload.';
}

// Display status message
echo $statusMsg;

标签: php

解决方案


 <?php
 $targetDir = "uploads/";
 $allowTypes = array('jpg','png','jpeg','gif');

 $statusMsg = $errorMsg = $insertValuesSQL = $errorUpload = $errorUploadType = '';
 if(!empty(array_filter($_FILES['files']['name']))){
     foreach($_FILES['files']['name'] as $key=>$val){

         $fileName = basename($_FILES['files']['name'][$key]);
         $expFileName=explode(".",$fileName);
         $fileName=rand().".".$expFileName[1];
         $targetFilePath = $targetDir . $fileName;

         $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
         if(in_array($fileType, $allowTypes)){
             move_uploaded_file($_FILES["files"]["tmp_name"][$key],$targetFilePath);
        //move_uploaded_file($_FILES["files"]["tmp_name"][$key], $targetFilePath);
         }else{
             $errorUploadType .= $_FILES['files']['name'][$key].', ';
         }
     }

 }else{
     $statusMsg = 'Please select a file to upload.';
 }

 // Display status message
 echo $statusMsg;
 ?>

推荐阅读