PHPでのファイル出力方法-用途別
- よくわからない。
- 大半はAPIでの方法
画像の表示
フロント
- vue等で
<img :src="varsrc">みたいに書くとき。 - Auhorazationは使えない
PHP
$file_path = ''Storage/app/以下のパス"
$name = $claim_file_object['original_name'];
$mimeType = Storage::mimeType($file_path);
$headers = [['Content-Type' => $mimeType]];
$disposition = 'attachment';
return Storage::response($file_path, $name, $headers, $disposition);
これで普通に表示される。ダウンロードはできない。
ダウンロードするとき
APIでダウンロードしたいとき、
フロント側コード
async function fetchFileDownload(url: string, file_name: string = 'download-file'): Promise<void> {
return new Promise((resolve, reject) => {
if (waiting_assign) reject('waiting-redirect...');
let request_url = `${api_server_base_url}${url}`;
const token = getToken();
fetch(request_url, {
method: 'GET',
// cache: 'no-cache',
headers: {
// 'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
// Accept: '*/*',
'Access-Control-Allow-Origin': '*',
Authorization: `Bearer ${token}`,
},
})
.then(response => response.blob())
.then(blob => {
console.log(blob);
var url = window.URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = url;
a.download = file_name;
document.body.appendChild(a); // we need to append the element to the dom -> otherwise it will not work in firefox
a.click();
a.remove(); //afterwards we remove the element again
nextTick(() => {
resolve();
});
})
.catch(e => {
reject(e);
});
});
}
PHP側
$file?_pathはStorage::pathで取ってきている。
$headers = [
'Content-Description' => 'File Transfer',
'Content-Type' => 'application/octet-stream',
'Content-Disposition' => "attachment; filename=\"{$orignal_name}\"",
'Expires' => $claim_file_object->created_at,
];
return response()->file($file_path, $headers);
Spreadsheetのダウンロード処理
public function itemExcelDownload(OrdersIDRequest $request) {
$oid = $request->id;
$data = OrderItem::query()
->where('orders_id', $oid)
->orderBy('no')
->get();
$file_out_path = self::ConvertExcelDownload($data);
$headers = [
'Expires' => date('YmdHis'),
'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'Content-Disposition' => 'attachment;filename="awh-item-' . date("md-Hi") . '.xlsx"',
'Cache-Control' => 'max-age=0'
];
return response()->file(Storage::path($file_out_path), $headers);
Storage::delete($file_out_path);
exit;
}
jsに慣れてるから、returnすると関数終了するかと思ったけど違うみたい