猿问

下载 CSV 文件的流响应

我正在尝试从服务器流式传输大型 CSV。我加载一个 JSON 文件,将其转换为数组,然后将其作为 CSV 进行处理。从前端,我通过单击按钮调用以下内容


downloadCSVData() {

    axios({

        url: '/downloadCSVData',

        method: 'GET'

    }).then((response) => {

        console.log(response)

    });

}

然后这个函数执行以下操作


public function downloadCSVData()

{

    //load JSON file

    $data = file_get_contents($file_path, true);


    //Convert file to array

    $array = json_decode($data, true);


    $headers = [

        'Cache-Control'       => 'must-revalidate, post-check=0, pre-check=0'

        ,   'Content-type'        => 'text/csv'

        ,   'Content-Disposition' => 'attachment; filename=galleries.csv'

        ,   'Expires'             => '0'

        ,   'Pragma'              => 'public'

    ];


    $response = new StreamedResponse(function() use($array){

        // Open output stream

        $handle = fopen('php://output', 'w');


        // Add CSV headers

        fputcsv($handle, array_keys($array['element'][0]), ',');


        foreach ($array['element'] as $key => $row) {

            fputcsv($handle, $row);

        }


        // Close the output stream

        fclose($handle);

    }, 200, $headers);


    return $response->send();

}

现在在前端,在控制台中,我可以看到按照需要的方式打印响应。然而,根据我的理解,后端应该触发要下载的文件,而这并没有发生。


我在这里遗漏了什么,如何将其作为物理文件下载到前端?


慕的地8271018
浏览 134回答 1
1回答

智慧大石

如果您直接访问了 URL,您的 PHP 设置应该可以强制下载。但是你已经在一个完全加载的 HTML 页面中,所以你需要使用这个<iframe>技巧来下载文件。这将允许浏览器接收传入的数据,就像您打开了一个新的浏览器窗口一样。尝试将您的下载功能更改为:downloadCSVData() {&nbsp; &nbsp; $('<iframe />')&nbsp; &nbsp; &nbsp; &nbsp; .attr('src', '/downloadCSVData')&nbsp; &nbsp; &nbsp; &nbsp; .hide()&nbsp; &nbsp; &nbsp; &nbsp; .appendTo('body');}
随时随地看视频慕课网APP
我要回答