Динамически создавайте файл как объект File, а затем публикуйте

Очевидно, немного сложнее динамически создать файл в SS4

$folder = Folder::find_or_make('Cards');
$filename = 'myimage.jpg';
$contents = file_get_contents('http://example.com/image.jpg');
$pathToFile = Controller::join_links(Director::baseFolder(), ASSETS_DIR, $folder->Title, $filename);
file_put_contents($pathToFile, $contents);

$image = Image::create();

$image->ParentID = $folder->ID;
$image->Title = "My title";
$image->Name = $filename;
$image->FileFilename = 'Cards/' . $filename;
$image->write();

Member::actAs(Member::get()->first(), function() use ($image, $folder) {
    if (!$image->isPublished()) {
        $image->publishFile();
        $image->publishSingle();
    }
    if (!$folder->isPublished()) {
        $folder->publishSingle();
    }
});

Выше, создает файл, как ожидается в /assets/Cards/myimage.jpg и публикует это нормально

Однако все предварительные просмотры пустые, поэтому файл явно не найден:

Все превью пустые

Любая идея, что я упустил при создании Image объект?

1 ответ

Решение

Это должно работать:

$folder = Folder::find_or_make('Cards');
$contents = file_get_contents('http://example.com/image.jpg');

$img = Image::create();
$img->setFromString($contents, 'image.jpg');
$img->ParentID = $parent->ID;
$img->write();

// This is needed to build the thumbnails
\SilverStripe\AssetAdmin\Controller\AssetAdmin::create()->generateThumbnails($img);
$img->publishSingle();

FYI: $img->Filename более не существует. Image или же File объект имеет File свойство, которое является составным полем типа DBFile, Эти составные поля содержат имя файла, хэш и вариант... Таким образом, вы должны использовать составное поле для адресации этих полей.

Другие вопросы по тегам