SilverStripe UploadField文件自动重命名

时间:2017-04-05 16:44:03

标签: php forms silverstripe

我在前端制作了一个表单来上传一些图片。我的想法是自动重命名上传到唯一ID的所有文件。

我查看了SilverStripe API,但我没有看到任何相关内容。 UploadField API

这可能吗?

2 个答案:

答案 0 :(得分:2)

以下是我的解决方案,在Silverstripe 3.X中,我们必须使用另一个类扩展UploadField。然后将''saveTemporaryFile''函数复制到其中。

在“尝试”之前,只需添加:

$ext = array_reverse(explode('.',$tmpFile['name'])); // explode filename into array, reverse array, first array key will then be file extension
$tmpFile['name'] = hash_hmac('sha256', $tmpFile['name'], '12345') . '.' . $ext[0];

结果:

class RandomNameUploadField extends UploadField {


protected function saveTemporaryFile($tmpFile, &$error = null) {

    // Determine container object
    $error = null;
    $fileObject = null;

    if (empty($tmpFile)) {
        $error = _t('UploadField.FIELDNOTSET', 'File information not found');
        return null;
    }

    if($tmpFile['error']) {
        $error = $tmpFile['error'];
        return null;
    }

    // Search for relations that can hold the uploaded files, but don't fallback
    // to default if there is no automatic relation
    if ($relationClass = $this->getRelationAutosetClass(null)) {
        // Create new object explicitly. Otherwise rely on Upload::load to choose the class.
        $fileObject = Object::create($relationClass);
    }

    $ext = array_reverse(explode('.',$tmpFile['name'])); // explode filename into array, reverse array, first array key will then be file extension
    $tmpFile['name'] = hash_hmac('sha256', $tmpFile['name'], '12345') . '.' . $ext[0];

    // Get the uploaded file into a new file object.
    try {
        $this->upload->loadIntoFile($tmpFile, $fileObject, $this->getFolderName());
    } catch (Exception $e) {
        // we shouldn't get an error here, but just in case
        $error = $e->getMessage();
        return null;
    }

    // Check if upload field has an error
    if ($this->upload->isError()) {
        $error = implode(' ' . PHP_EOL, $this->upload->getErrors());
        return null;
    }

    // return file
    return $this->upload->getFile();
}



}

感谢@3dgoo给我一部分解决方案!

答案 1 :(得分:0)

我现在还没有关于API的信息,但是通过一些代码,我能够做到这一点。

你有两种可能性。

首先使用数据库。

仅使用代码:

$directory = '/teste/www/fotos/';
$files = glob($directory . '*.jpg');

if ( $files !== false )
{
    $filecount = count( $files );
    $newid = $filecount+1;
    $new_name = "foto_".$newid;
    $target_file =  $directory."/".$new_name;
    move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);

}
else
{
     $new_name = "foto_1";
     $target_file =  $directory."/".$new_name;
     move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
}

我的例子是jpeg,但你可以寻找大厅类型。