panthro's avatar

How to upload files from a URL?

I can upload files like this:

Storage::putFileAs(config('media.path'), $file, $this->getFilename());

$file can either be a URL or UploadedFile.

But when the $file is a URL, I fail to get some information from my $this->getFilename() method:

 public function getFilename()
    {
        return "{$this->getName()}.{$this->getExtension()}";
    }
    
    public function getName()
    {
        return $this->name;
    }

    public function getExtension()
    {
        return $this->file->extension();
    }

It appears that $this->file->extension() only works on UploadedFile.

What should I do?

Should I create an UploadedFile? create a File instance? Something else?

0 likes
3 replies
s4muel's avatar

what is $this in your context, formRequest? just write a condition, if the $file is a string (url), parse the filename/extension from there, if it is an instance of UploadedFile, use like before

panthro's avatar

@s4muel ok, but how do I get the URL image as a file so I can do things to it such as ->getExtension() or ->getMimeType()?

s4muel's avatar
s4muel
Best Answer
Level 50

@panthro @panthro is mimetype enough for you? you can get the filename and extension from the url, you can get the mimetype using the get_headers php function

$headers=get_headers("https://example.com/filename.jpg");
dd($headers); // check the `Content-Type`

but you can also download it somewhere and use Storage::mimeType($path) and other methods from Storage Facade

1 like

Please or to participate in this conversation.