Laravel 4 get image from url

OK, so when I want to upload an image. Usually I do something like:

$file = Input::file('image'); $destinationPath = 'whereEver'; $filename = $file->getClientOriginalName(); $uploadSuccess = Input::file('image')->move($destinationPath, $filename); if( $uploadSuccess ) { // save the url } 

This works great when the user uploads an image. But how to save image from URL ???

If I try something like:

 $url = 'http://www.whereEver.com/some/image'; $file = file_get_contents($url); 

and then:

 $filename = $file->getClientOriginalName(); $uploadSuccess = Input::file('image')->move($destinationPath, $filename); 

I get the following error:

 Call to a member function move() on a non-object 

So how to load image from url with laravel 4 ??

Help me help.

+4
source share
3 answers

I do not know if this will help you, but you can look in the Library of Interventions . It was originally intended to be used as an image processing library, but it does provide image retention from the URL:

 $image = Image::make('http://someurl.com/image.jpg')->save('/path/saveAsImageName.jpg'); 
+10
source

The Laravel Input :: file method is only used when downloading files with a POST request, I think. The error you get is because file_get_contents is not returning the laravel class to you. And you do not need to use the move () method or its equivalent, because the file that you get from url does not load into your tmp folder.

Instead, I think you should use PHP to upload the image file via the URL that is described here.

how

 // Your file $file = 'http://....'; // Open the file to get existing content $data = file_get_contents($file); // New file $new = '/var/www/uploads/'; // Write the contents back to a new file file_put_contents($new, $data); 

I can’t check it now, but this is not a bad decision. Just get the data from the url and then save it if you want.

+1
source
  $url = "http://example.com/123.jpg"; $url_arr = explode ('/', $url); $ct = count($url_arr); $name = $url_arr[$ct-1]; $name_div = explode('.', $name); $ct_dot = count($name_div); $img_type = $name_div[$ct_dot -1]; $destinationPath = public_path().'/img/'.$name; file_put_contents($destinationPath, file_get_contents($url)); 

this will save the image in your / public / img, the file name will be the original file name, which is 123.jpg for the above case.

the name of the image recipient indicated here

+1
source

Source: https://habr.com/ru/post/1492606/


All Articles