0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

過去ログ 2023 PHP

0
Posted at

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すると関数終了するかと思ったけど違うみたい

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?