如何在将文件上传到服务器之前重命名?

时间:2016-08-05 17:15:41

标签: php

我尝试过以下方式上传文件,但文件没有从我的目标文件夹上传,我一直在努力重命名文件..实际上'filebutton'是我的输入元素名称..

我的上传脚本

$target_dir = "../resumes/";
                    $file_name = $cand_arrval['resume_title'].$cand_arrval['resume_name'];
                    $filename = basename($_FILES["filebutton"]["name"]);
                    $filename = $file_name . strrchr($filename, '.');
                    $target_file = $target_dir .$filename;

                $uploadOk = 1;
                echo $FileType = pathinfo($target_file,PATHINFO_EXTENSION);

                $selector = "";
                // Check if file already exists
                if (file_exists($target_file)) {
                    $uploadOk = 0;

                }
                // Check file size
                if ($_FILES["filebutton"]["size"] > 500000) {
                    $uploadOk = 0;

                }
                // Allow certain file formats
                if($FileType != "doc" && $FileType != "docx" && $FileType != "txt") {
                    $uploadOk = 0;

                }
                // Check if $uploadOk is set to 0 by an error
                if ($uploadOk == 0) {
                    $prop->call_rollback();

                // if everything is ok, try to upload file
                } else {
                    $temp = explode(".", $_FILES["filebutton"]["name"]);
                    $extension = end($temp);


                    if (move_uploaded_file($_FILES["filebutton"]["tmp_name"],  $target_file)) {
                        echo "<center><div class='bg bg-success text-success' style='padding:5px;'>The file <b><i>". basename( $_FILES["filebutton"]["name"]). "</i></b> has been uploaded.!</div></center>";
                    } else {
                        echo "<div class='bg bg-danger text-warning' style='padding:5px;'>Sorry, there was an error uploading your file.</div>";
                    }
                }

$file_name实际上是我的重命名文字。如果有任何简单的方法建议我重命名原始文件名...

2 个答案:

答案 0 :(得分:0)

您可以在重命名文件时添加所需的文件扩展名.docx,只要您在该位置没有该名称的文件夹即可。

$target_file = $target_dir . "$file_name.docx";

答案 1 :(得分:0)

试试这个

$allowed_file_types = array ('doc', 'docx', 'txt');

if (!in_array($extension, $allowed_file_types) || $_FILES["filebutton"]["size"] > 500000 ) {
$prop->call_rollback();

} else {

   .....
}