动态创建文件作为 File 对象,然后发布
Create file dynamically as File object and then publish
在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
对象时遗漏了什么吗?
这应该有效:
$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();
仅供参考:$img->Filename
不再存在。 Image
或 File
对象有一个 File
属性,它是类型 DBFile
的复合字段。这个复合字段包含文件名、哈希和变体……
所以你应该使用复合字段来解决这些字段。
在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
对象时遗漏了什么吗?
这应该有效:
$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();
仅供参考:$img->Filename
不再存在。 Image
或 File
对象有一个 File
属性,它是类型 DBFile
的复合字段。这个复合字段包含文件名、哈希和变体……
所以你应该使用复合字段来解决这些字段。