Upload Image/File from URL

Hello.

I have an action on Edit Resource where i randomly download an image from web and upload it to the field but its not working.. what i am doing wrong.

Here is what i am trying..

filePath = UrlUploadedFile::createFromUrl($imageLink)->store('posts/featured_images');
// $file = UrlUploadedFile::createFromUrl($imageLink);

// $this->record->featured_image = $filePath;
// $this->record->featured_image = $file;
$this->record->featured_image = TemporaryUploadedFile::createFromLivewire($filePath);
$this->record->save();

$this->refreshFormData([
    'featured_image',
]);

class UrlUploadedFile extends UploadedFile
{
    public static function createFromUrl(string $url, string $originalName = '', string $mimeType = null, int $error = null, bool $test = false): self
    {
        if (! $stream = @fopen($url, 'r')) {
            throw new Exception('Can\'t open file from url ' . $url . '.');
        }

        $tempFile = tempnam(sys_get_temp_dir(), 'url-file-');

        file_put_contents($tempFile, $stream);

        return new static($tempFile, $originalName, $mimeType, $error, $test);
    }
}
Was this page helpful?