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

时间:2017-05-27 07:10:27

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

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

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

2 个答案:

答案 0 :(得分:1)

我评论的一个例子:

要上传的文件,请致电image_10.jpg

你想到的文件名imag_xpto.jpg

要更改的代码:

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

如果您想要一个字段来提供新名称,您只需要在html中创建一个输入字段并使用此代码来获取它。

帖子代码:

HTML:

$target_new_name = $_POST['inputfieldname'];

PHP:

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

您的代码包含一些调试和改进代码的提示

{{1}}

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

简单的方法。有任何问题,请问我会尽力回答

答案 1 :(得分:0)

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

           ballDisplay.setImageDrawable(
                   this.getResources()
                  .getDrawable(ballArray[number]);

当我使用下面的表单测试时,上述工作正常 - 唯一的另一个区别是我为测试目的设置为<?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