我有一個任務,需要上傳帶有數字的相同檔案名。例如,如果我上傳標題為“cv.pdf”的檔案 1,則第二個檔案應命名為“cv.pdf(1)”,下一個檔案應為“cv.pdf(2)”,依此類推。
我嘗試了很多方法,但仍然無法解決。可以請一些人幫助我達到預期的目標。這是我的
上傳.php
<?php
$json = array();
if(!empty($_FILES['upl_file'])){
$dir = "./uploads/";
$allowTypes = array('jpg', 'png', 'jpeg', 'gif', 'pdf', 'doc', 'docx');
$fileName = basename($_FILES['upl_file']['name']);
$filePath = $dir.$fileName;
$actual_name = pathinfo($filePath,PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo($filePath, PATHINFO_EXTENSION);
$i = 1;
while(file_exists("./uploads/".$actual_name.".".$extension))
{
$actual_name = (string)$original_name.$i;
$name = $actual_name.".".$extension;
$i ;
}
if(in_array($extension, $allowTypes)){
// Upload file to the server
if(move_uploaded_file($_FILES['upl_file']['tmp_name'], $filePath)){
$json = 'success';
} else {
$json = 'failed';
}
}
}
header('Content-Type: application/json');
echo json_encode($json);
?>
uj5u.com熱心網友回復:
我認為glob函式是你的救星。
而不是:
$i = 1;
while(file_exists("./uploads/".$actual_name.".".$extension))
{
$actual_name = (string)$original_name.$i;
$name = $actual_name.".".$extension;
$i ;
}
你應該使用:
$count = count(glob("./uploads/".$actual_name."*.".$extension));
//Check the * after the name
//EDIT: Before add the count, check if its not zero(0)
$actual_name = "{$name}".( $count > 0 ? "({$count})" : "").".{$extension}";
最后但并非最不重要的是,您應該更改檔案的最終名稱:
if(move_uploaded_file($_FILES['upl_file']['tmp_name'], $filePath))
//filePath has the old name
if(move_uploaded_file($_FILES['upl_file']['tmp_name'], $dir.$actual_name))
//newPath with count in the name
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/397907.html
