【问题标题】:Laravel 4 get image from urlLaravel 4 从 url 获取图像
【发布时间】:2013-07-20 12:31:32
【问题描述】:

好的,所以当我想上传图片时。我通常会这样做:

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

if( $uploadSuccess ) {
    // save the url
}

当用户上传图片时,这可以正常工作。但是如何从 URL 中保存图像???

如果我尝试类似:

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

然后:

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

我收到以下错误:

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

那么,如何使用 laravel 4 从 URL 上传图片??

非常感谢艾米的帮助。

【问题讨论】:

    标签: image upload laravel laravel-4


    【解决方案1】:

    我不知道这是否会对您有很大帮助,但您可能想查看Intervention Library。它最初打算用作图像处理库,但它提供了从 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));
    

    这会将图像保存到您的/public/img,文件名将是原始文件名,对于上述情况为123.jpg。

    here引用的get图片名称

    【讨论】:

      【解决方案3】:

      我认为 Laravel 的 Input::file 方法仅在您通过 POST 请求上传文件时使用。你得到的错误是因为 file_get_contents 没有返回你 laravel 的类。而且您不必使用 move() 方法或者它是模拟的,因为您从 url 获得的文件不会上传到您的 tmp 文件夹。

      相反,我认为您应该使用这里描述的PHP upload an image file through url

      喜欢:

      // 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);
      

      我现在无法检查,但这似乎是一个不错的解决方案。只需从 url 获取数据,然后将其保存在任何你想要的地方

      【讨论】:

      • $new 必须是文件名,而不是目录
      猜你喜欢
      • 2015-01-29
      • 2021-11-21
      • 2012-05-04
      • 2011-08-22
      • 1970-01-01
      • 2015-04-18
      • 1970-01-01
      • 2010-10-30
      相关资源
      最近更新 更多