2013-07-21 56 views
4

好的,所以當我想上傳圖片。我通常做類似的東西:Laravel 4從網址獲取圖片

$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?

艾米非常感謝。

回答

1

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數據,然後將其保存等。無論您想

+1

$新的必須是一個文件名,而不是目錄 –

1
 $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)); 

這將圖像保存到你的/公/ IMG,文件名會被123.jpg針對上述案例的原始文件名。

的獲取圖片名來自here

10

提到我不知道這是否會幫助你很多,但你可能想看看Intervention Library。它原本打算用作圖像處理庫,但它提供了從URL保存圖像:

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

這包做這項工作。 – Ali