iT邦幫忙

0

[Laravel] 從url下載檔案/儲存檔案

Laravel

前言

目的是將前端看到的 url圖片儲存在本機 sever。

讀取圖片

目前有兩種做法可以取得圖片:file_get_contents 和 fopen,皆是 php 的內建函式。

  • file — Reads entire file into an array
  • file_get_contents — Reads entire file into a string
  • fopen — Opens file or URL

fopen

$file = fopen ($url, 'rb');

file_get_contents

$contents = file_get_contents($url);

儲存圖片

存 url 的圖

也有兩種做法:

File open

$file = fopen ($url, 'rb');
if ($file) {
    $newf = fopen ($newfname, 'wb');
    if ($newf) {
        while(!feof($file)) {
            fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
        }
    }
}
if ($file) {
    fclose($file);
}
if ($newf) {
    fclose($newf);
}

$newfname = '../public/storage/image.'.File::extension(public_path($url));
File::extension(public_path($url)) 取得副檔名

Storage

Storage 是 laravel寫好的 Facades. 用 put/get 存取檔案
Storage將檔案存在storage/app/public目錄下,當我們執行php artisan storage:link,會建立一個 symbolic link,從 public/storage 連結到真正存檔的地方(storage/app/public)。

  • 用 Storage 介面
$contents = file_get_contents($url);
$name = substr($url, strrpos($item_info->pic, '/') + 1);//從url取得檔名
$stored = Storage::put('public/'.$name, $contents);

存 client 上傳的圖

  • 用 store method
$imageURL = request()->file('img')->store('public');
$reward->update(['reported_descript'=>$request->reported_descript,'img'=>asset('storage/' . substr($imageURL, 7))]);

讀取檔案

fopen

$file=fopen('../public/storage/'.explode('/', $item->img)[4], 'r');
$contents = fread($file,filesize('../public/storage/'.explode('/', $item->img)[4]));

Storage

$contents = Storage::get('public/'.explode('/', $item->img)[4]);

送出檔案:

用 Guzzle 套件來發送帶有圖片的 request:

$file=fopen('../public/storage/'.explode('/', $item->img)[4], 'r');
$contents = fread($file,filesize('../public/storage/'.explode('/', $item->img)[4]));
$deliever_photo = new Client([
    'headers' => ['Authorization' => "Bearer ".env('STATION_KEY'),
                'Content-Type' => 'multipart/form-data']
]);
$response_img = $deliever_photo->request('POST', env('STATION_BASE_URL').'/api/image',
['multipart' => [

    [
        'name'     => "good_id",
        'contents' => $response_de->id
    ],
    [
        'name'     => "photo",
        'contents' => $contents,
        'filename' => $name,
        'headers' => ['Content-Type' => 'image/png']
    ],]
]);

尚未有邦友留言

立即登入留言