I want to save an image in my S3 using an URL.
Here is my code:
public function uploadFromUrl(string $url, string $path, string $filename): string
{
$contents = file_get_contents($url);
$storage_disk = 'local' === config('app.env') ? 'public' : 's3';
Storage::disk($storage_disk)->putFile($filename, $contents);
if ('production' === config('app.env')) {
$url = Storage::disk($storage_disk)->url($path.'/'.$filename);
return str_replace(config('filesystems.disks.s3.url'), config('filesystems.disks.s3.cloudfront_url'), $url);
}
return Storage::disk($storage_disk)->url($path.'/'.$filename);
}
I receive the follow error:
code: "INVALID_ARGUMENT_EXCEPTION" message: "Malformed UTF-8 characters, possibly incorrectly encoded"
Use put()
instead of putFile()
Storage::disk($storage_disk)->put($filename, $contents);
public function put($path, $contents, $lock = false)
{
return file_put_contents($path, $contents, $lock ? LOCK_EX : 0);
}