Laravel
目的是將前端看到的 url圖片儲存在本機 sever。
目前有兩種做法可以取得圖片:file_get_contents 和 fopen,皆是 php 的內建函式。
$file = fopen ($url, 'rb');
$contents = file_get_contents($url);
也有兩種做法:
$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 是 laravel寫好的 Facades. 用 put/get 存取檔案
Storage將檔案存在storage/app/public
目錄下,當我們執行php artisan storage:link
,會建立一個 symbolic link,從 public/storage
連結到真正存檔的地方(storage/app/public)。
$contents = file_get_contents($url);
$name = substr($url, strrpos($item_info->pic, '/') + 1);//從url取得檔名
$stored = Storage::put('public/'.$name, $contents);
$imageURL = request()->file('img')->store('public');
$reward->update(['reported_descript'=>$request->reported_descript,'img'=>asset('storage/' . substr($imageURL, 7))]);
$file=fopen('../public/storage/'.explode('/', $item->img)[4], 'r');
$contents = fread($file,filesize('../public/storage/'.explode('/', $item->img)[4]));
$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']
],]
]);