如何将上传文件的名称更改为'job_id'.extension?

时间:2015-05-07 04:53:08

标签: php mysql database file primary-key

我想更改用户上传到'job_id'.fasta的文件的名称。现在它只是保持为用户上传时所称的任何内容。我还想将.fasta的扩展名保留在文件中。

此表格来自home.php。它是用户使用

上传文件的表单
<form enctype="multipart/form-data" action="upload.php" method="POST" class="form-inline">
                    <input type="file" name="fileToUpload" id="fileToUpload" class="form-control"/>
                            <input type="submit" value="upload" name="upload" class="form-control"/>
                            <input type="reset" value="reset" name="reset" class="form-control"/>
            </form>

此文件为upload.php。我的意见将解释我的思考过程。但如果有人能帮助我完成它,我将非常感激。

<?php

//get the max job_id from the Job table
$fileID = mysqli_query("SELECT MAX(job_id) FROM Job");

//I have to increment it once because we do not actually insert a new job_id yet.
$fileID = $fileID + 1;

// declare the file path
$target_dir = "uploads/";

//here we are creating the file name. I think I need the change something here
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

//get the file extension
$FileType = pathinfo($target_file,PATHINFO_EXTENSION);


//$target_file = $target_dir . $fileID . "'.'" $FileType;

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


// Allow certain file formats
if($FileType != "fasta" ) {
echo "Sorry, only fasta files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file))   {

        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
header('Location: blast.php');
?>

2 个答案:

答案 0 :(得分:0)

只需重命名生成新文件名,扩展名设置为目标。试试 -

//get the max job_id from the Job table
$fileID = mysqli_query("SELECT MAX(job_id) FROM Job");

//I have to increment it once because we do not actually insert a new job_id yet.
$fileID = $fileID + 1;

// declare the file path
$target_dir = "uploads/";

//get the file extension
$ext = explode('.', $_FILES["fileToUpload"]["name"]);
$fileName = $fileID.'.'.$ext[count($ext)-1];
//here we are creating the file name. I think I need the change something here
$target_file = $target_dir . $fileName;


//$target_file = $target_dir . $fileID . "'.'" $FileType;

$uploadOk = 1;

答案 1 :(得分:0)

尝试这种非常简单的方法。

//get the max job_id from the Job table
$fileID = mysqli_query("SELECT MAX(job_id) FROM Job");

//I have to increment it once because we do not actually insert a new job_id yet.
$fileID = $fileID + 1;

// declare the file path
$target_dir = "uploads/";

//here we are creating the file name. 
$file = explode('.', $_FILES["fileToUpload"]["name"]);
$filename = $file[0].time().$file[1];

$target_file = $target_dir . $filename;