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]);
$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
$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;
?>
推荐阅读
- php - 如何修复 PHP 通知:“尝试获取非对象的属性”(解析 XML)
- java - 未找到模块:javafx.controls
- r - 将 dplyr::count_ 应用于许多数据帧
- python - 用 Seaborn 绘制多个实验记录的统计信息
- bluetooth - 直接发送一个裸 HCI_ACL 数据包
- c++ - 强制构造一个全局对象
- c# - C#如何动态检测泛型类型
- streaming - streamlabs streamboss 名称更改
- intellij-idea - 如何将 JAXB 导入 Java 11 IntelliJ (Gradle) 项目?
- node.js - 在 Node Js 中处理基于令牌的授权