我可以使用表单字段重命名上传图像文件吗?

Can I Use A Form Field To Rename An Upload Image File?

我的表单中有一个 'Upload-File' 字段供网站访问者上传图片。

    <input type="file" name="fileToUpload" id="fileToUpload">

目前,文件保存到我的服务器时使用的是与上传时相同的'name'。

我想在我的表单中添加一个输入字段(如下所示),以便用户可以为 [image] 文件输入一个新的 'name'。

    <input name="imageRename" id="imageRename">

我需要一些关于更改当前 php 代码以在文件保存到我的服务器之前重命名文件的建议。

这是图像处理的当前 php 代码:

    <?php 
$target_dir = "articles/article-images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if(isset($_POST["submit"]))
{
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); 
    if($check !== false)
    {
        echo "". $check[""].""; $uploadOk = 1;
    } 
    else
    {
        echo "&#xd7; FILE IS NOT AN IMAGE"; $uploadOk = 0;
    } 
}
if(file_exists($target_file))
{
    echo "&#xd7; THIS IMAGE ALREADY EXIST ON SERVER"; $uploadOk = 0;
}
if ($_FILES["fileToUpload"]["size"] > 500000)
{
    echo "&#xd7; FILE IS TOO LARGE"; $uploadOk = 0;
}
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" )
{
    echo "&#xd7; ONLY JPG, JPEG, PNG & GIF FILES ARE PERMITTED"; $uploadOk = 0; 
}
if ($uploadOk == 0)
{
    echo "&#xd7; IMAGE WAS NOT UPLOADED";
}
else
{
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file))
    {
        echo '<img class="fixed-ratio-resize" src="../../articles/article-images/'. basename( $_FILES["fileToUpload"]["name"]). '">';
    } 
    else
    {
        echo "&#xd7; IMAGE WAS NOT UPLOADED";
    }
} 
    ?>

我的评论示例:

要上传的文件调用image_10.jpg

你想要的文件名imag_xpto.jpg

要更改的代码:

$target_dir = "articles/article-images/";
$target_new_name = "imag_xpto.jpg";
//your code...
$target = $target_dir.$target_new_name;
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)){
//Your code...

如果你想要一个字段给新的名字,你只需要在你的html中创建一个输入字段并使用这个代码来获取它。

代码 post:

HTML:

<input type =  "text" name = "inputfieldname">

PHP:

$target_new_name = $_POST['inputfieldname'];

您的代码以及一些调试和改进代码的技巧

<?php 

if(isset($_POST["submit"]))
{
     $target_new_name = $_POST["inputfieldname"]; //you can and you should  protect, if you are sending null or empty or undefined it can cause problems in the future. For protect you can use isset and verify if the name it's null or "".
$target_dir = "articles/article-images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$target_new_file_name =  $target_dir.$target_new_name.".".$imageFileType; // Check with an "error_log($target_new_file_name);" the string "$target_new_file_name". Because it is in the creation of the new string, that the problems occur 
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); 
    if($check !== false)
    {
        echo "". $check[""].""; $uploadOk = 1;
    } 
    else
    {
        echo "&#xd7; FILE IS NOT AN IMAGE"; $uploadOk = 0;
    } 
}
//if(file_exists($target_file)) - You should now verify that the new file name exists on the server

if(file_exists($target_new_file_name))
{
    echo "&#xd7; THIS IMAGE ALREADY EXIST ON SERVER"; $uploadOk = 0;
}
if ($_FILES["fileToUpload"]["size"] > 500000)
{
    echo "&#xd7; FILE IS TOO LARGE"; $uploadOk = 0;
}
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" )
{
    echo "&#xd7; ONLY JPG, JPEG, PNG & GIF FILES ARE PERMITTED"; $uploadOk = 0; 
}
if ($uploadOk == 0)
{
    echo "&#xd7; IMAGE WAS NOT UPLOADED";
}
else
{
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_new_file_name))
    {
        echo '<img class="fixed-ratio-resize" src="'.$target_new_file_name.'">'; // I'm not really sure about this part of the code, I'm used to another type of html creation in php
    } 
    else
    {
        echo "&#xd7; IMAGE WAS NOT UPLOADED";
    }
} 
    ?>

我还没有机会测试,所以代码中可能存在一些错误。

简单的方法。有什么问题,尽管问,我会尽力回答

您应该测试用户是否实际提交了新名称的值,如果没有则使用原始名称(或随机名称)。此外 - 您可以使用在 $_FILES 对象中找到的预定义错误特征来帮助处理。

<?php 

    $filefield='fileToUpload';
    $textfield='imageRename';

    /*
        function to return the reason for any failure
    */
    function uploaderror( $code ){ 
        switch( $code ) { 
            case UPLOAD_ERR_INI_SIZE: return "The uploaded file exceeds the upload_max_filesize directive in php.ini"; 
            case UPLOAD_ERR_FORM_SIZE: return "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"; 
            case UPLOAD_ERR_PARTIAL: return "The uploaded file was only partially uploaded"; 
            case UPLOAD_ERR_NO_FILE: return "No file was uploaded"; 
            case UPLOAD_ERR_NO_TMP_DIR: return "Missing a temporary folder"; 
            case UPLOAD_ERR_CANT_WRITE: return "Failed to write file to disk"; 
            case UPLOAD_ERR_EXTENSION: return "File upload stopped by extension"; 
            default: return "Unknown upload error";
        }
    }

    /*
        test that the required items are present in posted data
    */
    if( isset( $_FILES[ $filefield ],$_POST[ $textfield ] ) ){

        $target_dir = "articles/article-images/";
        $errors=array();

        /* set permitted file extensions - not foolproof btw */
        $allowed=array('jpg','jpeg','png','gif');

        /* get the properties of the uploaded file */
        $obj=(object)$_FILES[ $filefield ];
        $name=$obj->name;
        $tmp=$obj->tmp_name;
        $size=$obj->size;
        $error=$obj->error;
        $type=$obj->type;


        /*
            determine the new name of the file if the user supplied a new name or not
        */
        $newname = !empty( $_POST[ $textfield ] ) ? $_POST[ $textfield ] : false;
        $ext = pathinfo( $name, PATHINFO_EXTENSION );

        $name =( $newname ) ? $newname .= ".{$ext}" : $name;


        /* no errors so far, proceed with logical tests of your own */
        if( $error==UPLOAD_ERR_OK ){

            if( !in_array( $ext,$allowed ) ) $errors[]="&#xd7; ONLY JPG, JPEG, PNG & GIF FILES ARE PERMITTED";
            if( $size > 500000 )$errors[]="&#xd7; FILE IS TOO LARGE";
            if( !getimagesize( $tmp ) )$errors[]="&#xd7; FILE IS NOT AN IMAGE";
            if( !is_uploaded_file( $tmp ) )$errors[]="&#xd7; POSSIBLE FILE UPLOAD ATTACK";


            if( empty( $errors ) ){
                /*
                    set the new file location
                */
                $targetfile = $target_dir . DIRECTORY_SEPARATOR . $name;

                /*
                    save the file
                */
                $status = move_uploaded_file( $tmp, $targetfile );

                /*
                    determine what to do if it succeeded or not
                */
                if( $status ){
                    echo '<img class="fixed-ratio-resize" src="../../articles/article-images/'. basename( $name ). '" />';
                } else {
                    exit('error');
                }
            } else {/* edited: changed commas to periods */
                exit( '<pre>'.print_r($errors,1).'</pre>' );
            }
        } else {
            exit( uploaderror( $error ) );
        }
    }
?>

当我使用下面的表格对此进行测试时,上面的工作正常 - 唯一的区别是我为测试目的设置为 c:\temp\fileuploads 的目标目录路径。

    <form id='fileupload' action='/test/so_upload_image_target.php' method='post' enctype='multipart/form-data'>
        <h1>Upload an image - test</h1>
        <input type='file' name='fileToUpload' />
        <input type='text' name='imageRename' value='boobies' />
        <input type='submit' />
    </form>