简体   繁体   English

PHP:上传前重命名文件

[英]PHP: Rename file before upload

I'm trying to rename each file before uploading to Amazon S3. 我试图重命名每个文件,然后再上传到Amazon S3。

I am trying to use this exact method of which was answered by @Silvertiger: PHP - upload and overwrite a file (or upload and rename it)? 我正在尝试使用@Silvertiger回答过的确切方法:PHP- 上传并覆盖文件(或上传并重命名)?

If exists, rename to a random name although somehow it doesn't work. 如果存在,请重命名为随机名称,尽管它不起作用。

Here is the upload post Parameter from the Amazon S3 Class: 这是来自Amazon S3类的上传帖子参数:

public static function getHttpUploadPostParams($bucket, $uriPrefix = '', $acl = self::ACL_PRIVATE, $lifetime = 3600,
    $maxFileSize = 5242880, $successRedirect = "201", $amzHeaders = array(), $headers = array(), $flashVars = false)
    {
        // Create policy object
        $policy = new stdClass;
        $policy->expiration = gmdate('Y-m-d\TH:i:s\Z', (time() + $lifetime));
        $policy->conditions = array();
        $obj = new stdClass; $obj->bucket = $bucket; array_push($policy->conditions, $obj);
        $obj = new stdClass; $obj->acl = $acl; array_push($policy->conditions, $obj);

        $obj = new stdClass; // 200 for non-redirect uploads
        if (is_numeric($successRedirect) && in_array((int)$successRedirect, array(200, 201)))
            $obj->success_action_status = (string)$successRedirect;
        else // URL
            $obj->success_action_redirect = $successRedirect;
        array_push($policy->conditions, $obj);

        if ($acl !== self::ACL_PUBLIC_READ)
            array_push($policy->conditions, array('eq', '$acl', $acl));

        array_push($policy->conditions, array('starts-with', '$key', $uriPrefix));
        if ($flashVars) array_push($policy->conditions, array('starts-with', '$Filename', ''));
        foreach (array_keys($headers) as $headerKey)
            array_push($policy->conditions, array('starts-with', '$'.$headerKey, ''));
        foreach ($amzHeaders as $headerKey => $headerVal)
        {
            $obj = new stdClass;
            $obj->{$headerKey} = (string)$headerVal;
            array_push($policy->conditions, $obj);
        }
        array_push($policy->conditions, array('content-length-range', 0, $maxFileSize));
        $policy = base64_encode(str_replace('\/', '/', json_encode($policy)));

        // Create parameters
        $params = new stdClass;
        $params->AWSAccessKeyId = self::$__accessKey;
        $params->key = $uriPrefix.'${filename}';
        $params->acl = $acl;
        $params->policy = $policy; unset($policy);
        $params->signature = self::__getHash($params->policy);
        if (is_numeric($successRedirect) && in_array((int)$successRedirect, array(200, 201)))
            $params->success_action_status = (string)$successRedirect;
        else
            $params->success_action_redirect = $successRedirect;
        foreach ($headers as $headerKey => $headerVal) $params->{$headerKey} = (string)$headerVal;
        foreach ($amzHeaders as $headerKey => $headerVal) $params->{$headerKey} = (string)$headerVal;
        return $params;
    }

Here is @Silvertiger's method: 这是@Silvertiger的方法:

// this assumes that the upload form calls the form file field "myupload"
$name  = $_FILES['myupload']['name'];
$type  = $_FILES['myupload']['type'];
$size  = $_FILES['myupload']['size'];
$tmp   = $_FILES['myupload']['tmp_name'];
$error = $_FILES['myupload']['error'];
$savepath = '/yourserverpath/';
$filelocation = $svaepath.$name;
// This won't upload if there was an error or if the file exists, hence the check
if (!file_exists($filelocation) && $error == 0) {
    // echo "The file $filename exists";
    // This will overwrite even if the file exists
    move_uploaded_file($tmp, $filelocation);
}
// OR just leave out the "file_exists()" and check for the error,
// an if statement either way

This is my upload form: 这是我的上传表格:

    <form method="post" action="<?php echo $uploadURL; ?>" enctype="multipart/form-data">
<?php
    foreach ($params as $p => $v)
        echo "        <input type=\"hidden\" name=\"{$p}\" value=\"{$v}\" />\n";
?>
        <input type="file" name="file" />&#160;<input type="submit" value="Upload" />
    </form>

And this is the Input info: 这是输入信息:

public static function inputFile($file, $md5sum = true)
    {
        if (!file_exists($file) || !is_file($file) || !is_readable($file))
        {
            self::__triggerError('S3::inputFile(): Unable to open input file: '.$file, __FILE__, __LINE__);
            return false;
        }
        return array('file' => $file, 'size' => filesize($file), 'md5sum' => $md5sum !== false ?
        (is_string($md5sum) ? $md5sum : base64_encode(md5_file($file, true))) : '');
    }

You can do your renaming at this point in your code: 您现在可以在代码中进行重命名:

move_uploaded_file($tmp, $filelocation);

The $filelocation can be changed to whatever you want and the uploaded file will be renamed to that path. 可以将$filelocation更改为所需的内容,并将上载的文件重命名为该路径。

Edit : The S3::getHttpUploadPostParams method always uses the file name from the upload to create the S3 resource. 编辑S3::getHttpUploadPostParams方法始终使用上传中的文件名来创建S3资源。 To change that you have to copy the method but change this line: 要更改您必须复制方法但更改此行:

$params->key = $uriPrefix.'${filename}';

The '${filename} must be changed to a path of your choosing. 必须将'${filename}更改为您选择的路径。

Replace this: 替换为:

// Create parameters
$params = new stdClass;
$params->AWSAccessKeyId = self::$__accessKey;
$params->key = $uriPrefix.'${filename}';

with this: 有了这个:

function rand_string( $length ) {
            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  

            $size = strlen( $chars );
            for( $i = 0; $i < $length; $i++ ) {
                $str .= $chars[ rand( 0, $size - 1 ) ];
            }

            return $str;
        }       

        // Create parameters
        $params = new stdClass;
        $params->AWSAccessKeyId = self::$__accessKey;
        $params->key = $uriPrefix.rand_string(5).'${filename}';

You can easily put this code.. 100 percent working. 您可以轻松地放置此代码。.100%工作。

<?php
$file=$_FILES['file']['name'];
$path ="upload/".$file;
$ext=pathinfo($path,PATHINFO_EXTENSION);
$name=pathinfo($path,PATHINFO_FILENAME);
if(file_exists($path))
{
    echo "File alredy exists .So name is changed automatically & moved";
    $path1="upload/";
    $new_name=$path1.$name.rand(1,500).".".$ext;
    move_uploaded_file($_FILES['file']['tmp_name'],$new_name);
}
else
{
echo"uploaded Sucessfully without any change";
move_uploaded_file($_FILES['file']['tmp_name'],$path);
}
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM