下载文件laravel 5.7后重定向

时间:2020-02-12 06:56:24

标签: php laravel laravel-5 redirect routes

你好

希望你会做的很好。我想在文件下载后重定向到一条路由,但是我们知道,返回仅在控制器方法中起作用一次,我如何使用laravel 5.7做到这一点,我必须设置一个会话并显示当数据导出到txt文件中时它。我想要用post方法。 每件事都很好,但是重定向不起作用;

控制器方法

public function exportTxtProcess(Request $request)
{
    $table = $request->tblExportSelect;

    $destinationPath = public_path('/');

    $result;

    $outputs = DB::select("SELECT * FROM $table");

    $today = date("Y-m-d");
    $fileName = $table . "-" . $today;
    $fp = fopen($destinationPath . "$fileName.txt", "wb");

    foreach ($outputs as $output) {
        $output = (array)$output;

        @array_shift($output);

        $removeUserId = @$output['user_id'];
        $created_at = @$output['created_at'];
        $updated_at = @$output['updated_at'];

        if (($key = array_search($removeUserId, $output)) !== false) {
            unset($output[$key]);
        }
        if (($key1 = array_search($created_at, $output))) {

            unset($output[$key1]);
        }

        if (($key2 = array_search($updated_at, $output))) {

            unset($output[$key2]);
        }

        if (is_null($created_at) OR $created_at == '') {
            unset($output['created_at']);
        }

        if (is_null($updated_at) OR $updated_at == '') {
            unset($output['updated_at']);
        }


        $netResult = $this->getTableFields($table, $output);

        fwrite($fp, $netResult);

    }

    $result = fclose($fp);


    if ($result) {
        $pathToFile = $destinationPath . "$fileName.txt";

        $redirect = redirect()->back();
        $sess = Session::flash('success', 'Table exported successfully');
        return response()->download($pathToFile)->deleteFileAfterSend(true);


    }

}

预先感谢

1 个答案:

答案 0 :(得分:0)

您只能有1个响应,因此不可能指示两次 返回。您可以做的就是设置您想要的文件名 下载到会话变量中,然后重定向回任何页面。 在重定向页面中,您可以随即显示消息 自动下载文件。

以下是该主题的一些线索:

How do I redirect after download in Laravel?

PHP generate file for download then redirect