SilverStripe UploadField 文件自动重命名

SilverStripe UploadField file auto renaming

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

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

这可能吗?

我现在不了解 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,但您可以查找大厅类型。

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

就在''try''之前,只需添加:

$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给我解决方案的一部分!