Save external image from url in kirby 3

dear @texnixe,

a few years ago you helped someone with this topic but for kirby2

could you please give me some advice on how to do this for kirby3? the image gets saved but I’ve been struggling for some time now with the File part. right now i have this:

//this part works fine
$imageName = F::safeName('social_preview-' . $page->title());
$imageData = file_get_contents($external_url);
file_put_contents($page->root() . DS . $imageName . '.jpg', $imageData);

//but this is not working :( I am not sure what to set for parent and source.
//and does filename need the .jpg extension or full path? or just the name like now?
$image = new File([
            'source'   => $external_url,
            'parent'   => $exhibit->parentModel(),
            'filename' => $imageName,
            'template' => 'exhibit_preview',
        ]);

so I end up with a jpg in the page folder, but there is no .txt file for it.

These are the available parameters: new File() | Kirby CMS

So the minimum you need to pass is the filename and the parent, which would be $page in your example, I guess.

yes I have been going through the PHP classes but it is not working. let me try again with only those two params. I also tried this

$image = $page->createFile([
            'source'   => $external_url,
            'parent'   => $exhibit->parentModel(),
            'filename' => $imageName,
            'template' => 'exhibit_preview',
        ]);

but then it did not work either.

ok i just tried it and it is the same. no errors are thrown or anything, but the txt file is not there

c_exhibit is my page and the jpg is there, but no social_preview-social-embed.jpg.txt file is created

Bildschirm­foto 2022-12-14 um 19.20.05

The corresponding txt file needs to be created separately with $file->update()

oh excellent, it works now! i thought the file gets created automatically like with createFile. thank you very much!!

final code:

$imageData = file_get_contents($external_url);
file_put_contents($page->root() . DS . $imageName . '.jpg', $imageData);

$image = new File([
            'parent'   => $page,
            'filename' => $imageName.'.jpg',
            'template' => 'exhibit_preview',
]);

$image->update();