Laravel 4 get image from url

♀尐吖头ヾ 提交于 2019-12-07 10:39:09

问题


OK so when I want to upload an image. I usually 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 fine when the user uploads the image. But how do I save an image from an 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 do I upload an image from a URL with laravel 4??

Amy help greatly appreciated.


回答1:


I don't know if this will help you a lot but you might want to look at the Intervention Library. It's originally intended to be used as an image manipulation library but it provides saving image from url:

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



回答2:


        $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 to your /public/img, filename will be the original file name which is 123.jpg for the above case.

the get image name referred from here




回答3:


Laravel's Input::file method is only used when you upload files by POST request I think. The error you get is because file_get_contents doesn't return you laravel's class. And you don't have to use move() method or it's analog, because the file you get from url isn't uploaded to your tmp folder.

Instead, I think you should use PHP upload an image file through url what is described here.

Like:

// 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 right now but it seems like not a bad solution. Just get data from url and then save it whereever you want



来源:https://stackoverflow.com/questions/17776291/laravel-4-get-image-from-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!