簡體   English   中英

重命名上傳的文件(php)

[英]Rename uploaded file (php)

我正在嘗試重命名要上傳的文件。

我將上傳xml或pdf文件,並且希望將其保存在名為“ files / orderid /”的文件夾中,並且文件名也應為orderid .extension

文件上傳正常,並且使用正確的名稱創建了文件夾ID,但我嘗試重命名的所有方法均失敗。

下面是我的代碼。

// include database connection
 include 'config/database.php';

// get passed parameter value, in this case, the record ID
 $id=isset($_GET['orderid']) ? $_GET['orderid'] : die('FEJL: Ordren kunne ikke findes.');

// page header
 $page_title="Upload pdf og/eller xml fil";
 include_once "layout_head.php";

 echo "Ordrenummeret er ";
 echo $id;
 echo "<br>";

 if($_POST){

mkdir("files/$id");
$target_dir = "files/$id/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);


// Check if file already exists
if (file_exists($target_file)) {
    echo "Filen eksisterer allerede.";
    $uploadOk = 0;
}


// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Filen er for stor.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "xml" && $imageFileType != "pdf") {
    echo "Kun xml og pdf filer kan uploades.";
    $uploadOk = 0;
}


// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Filen blev ikke uploaded.";

// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "Filen ". basename( $_FILES["fileToUpload"]["name"]). " er uploaded.";
    } else {
        echo "Der skete en fejl ved upload, prøv igen.";
    }
}
}
?>

 <!DOCTYPE html>
 <html>
 <body>

 <form action="upload_files.php?orderid=<?php echo htmlspecialchars($id); ?>" method="post" enctype="multipart/form-data">
Vælg xml eller pdf fil:
<input type="file" name="fileToUpload" id="<?php echo htmlspecialchars($id); ?>">
<input type="submit" value="Upload fil" name="submit">
 </form>

 </body>
 </html>

重命名文件如下

$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$target_file = $target_dir . $id . '.' . $imageFileType;

接着

move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);

您將目標文件設置為文件名。 您應該設置一個不同的名稱。

嘗試這個:

$target_dir = "files/$id/";
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$target_file = "{$target_dir}{$id}.{$imageFileType};

謝謝家伙,這一切都有幫助。

我的解決方案是使用擴展名創建一個變量,然后在整個文件中使用它。

//Check file extension
$path = $_FILES["fileToUpload"]["name"];
$ext = pathinfo($path, PATHINFO_EXTENSION);

接着

move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "files/$id/$id.$ext"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM