【问题标题】:Can I Use A Form Field To Rename An Upload Image File?我可以使用表单字段重命名上传的图像文件吗?
【发布时间】:2017-05-27 07:10:26
【问题描述】:

我的表单中有一个“上传文件”字段供网站访问者上传图片。

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

目前,文件以与上传时相同的“名称”保存到我的服务器。

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

    <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";
    }
} 
    ?>

【问题讨论】:

  • 如果要重命名文件,请使用“move_uploaded_file”。您的目标文件名“$ target”将是您要保存文件的新名称和路径。

标签: php forms file-upload image-uploading buffering


【解决方案1】:

我的评论示例:

文件上传调用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中创建一个输入字段并使用这个代码来获取它。

发帖代码:

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";
    }
} 
    ?>

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

简单的方法。有什么问题就问吧,我会尽量回答的

【讨论】:

  • 感谢您的时间和建议 Jose。我试过你的代码。到目前为止没有运气。我想也许我仍然对您的编辑/添加的确切位置感到困惑。注意:我在帖子中包含的代码确实按照我需要的方式工作,除了名称更改。它的其余部分工作得很好。我只希望图像文件以基于表单输入字段的新名称保存。您是否可以在我的完整代码中包含您的编辑以实现这一目标?注意:另外...为了省点麻烦...将提供新文件名的表单文本字段命名为“timeValue”。
  • 如果你想这样,你需要把你的html从你的表单中。
  • 这是一个精简版的表单:
  • 这种方式可行,但是我很累,因为在我的国家已经是晚上了,所以可能会有一些错误,如果你有问题描述你遇到的问题,我会在稍后。
  • 非常感谢您回复我。我会测试你的编辑,看看我能走多远。无论哪种方式,我都会在这里发表评论。再次感谢兄弟。顺便说一句……你在哪个国家?
【解决方案2】:

您应该测试用户是否实际提交了新名称的值,如果不使用原始名称(或随机名称)。此外 - 您可以使用 $_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>

【讨论】:

  • 谢谢拉姆。即将测试您的代码。我假设您在哪里声明了 $textfield,我将用提供名称的文本字段的名称替换它,是吗?另外...我收到以下行的语法错误:exit('
    ',print_r($errors,1),'
    ');但无论如何我都会尝试代码。我会在反馈后立即回来。
  • 不幸的是,该代码不起作用。它不仅根本没有保存图像......它还导致我的html不显示。 html 文件确实保存到其正确的文件夹,但没有显示。并且图像没有保存或显示。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-27
  • 1970-01-01
  • 2023-01-13
  • 2020-04-21
  • 2014-01-20
  • 1970-01-01
相关资源
最近更新 更多