nanisore oishisou

Webエンジニアあるまさんのゆるふわ奮闘記。

safariで出力ファイルの拡張子に.htmlを付けられる時の対処法

対処方法1

出力処理の最後にexit;を足す。 ※ ただし、exitで処理をぶった切るので、middlewareでactionのafterにごちゃごちゃやってると、それもぶった切られる。

        // ファイル出力
        $fp = fopen('php://output', 'w+b');
        fwrite($fp, $csv);
        fclose($fp);
        exit;

【参考】 https://stackoverflow.com/questions/19363744/safari-adding-html-to-download

https://qiita.com/mata/items/6a30b65ecc71e02d447a

対処方法2

responseヘルパーを使ってレスポンスを返す

ex) csv

        $csv = FileUtils::createCsv($user_rows);
        
        return response($csv)->
            header('Content-Type', 'text/csv')->
            header(
                'Content-Disposition',
                'attachment; filename="'.$file_name.'.csv'.'"'
            );

ex) zip

        $headers = [
            'Content-Type' => 'application/zip',
            'Content-disposition' => 'attachment; filename*=UTF-8\'\''.rawurlencode($zipName),
            'Content-Length' => filesize($zipPath)
        ];

        return response()->download($zipPath, $zipName, $headers);

【キーワード】 safari Safari 出力 csv zip 出力 拡張子