代码之家  ›  专栏  ›  技术社区  ›  imin

return response()->下载(存储路径('app/files/gggusers.xlsx');显示的空白页

  •  0
  • imin  · 技术社区  · 5 年前

    我有这个密码

    return response()->download(storage_path('app/files/gggusers.xlsx'));
    

    在我的控制器里。它执行时没有任何问题,但它没有触发浏览器下载excel文件,而是显示一个空白的白色页面。我肯定文件名和位置是正确的,因为如果我只是更改文件名gggusers.xlsx对于其他文件或我删除该文件,Laravel将显示此错误

    The file "D:\web\speak\storage\app/files/gggusers.xlsx" does not exist

    0 回复  |  直到 5 年前
        1
  •  0
  •   imin    5 年前

    事实证明问题的发生是因为我

    return response()->download(storage_path('app/files/gggusers.xlsx'));
    

    在另一个函数中,并从路由中加载的函数调用它,如下所示:

    class HomeController extends Controller
    {
        /**
         * Create a new controller instance.
         *
         * @return void
         */
        public function __construct()
        {
            $this->middleware('auth');
        }
    
        public function index(){
            $this->download();
        }
    
        public function download(){
            return response()->download(storage_path('app/files/gggusers.xlsx'));
        }
    }
    

    上面的代码将显示一个空白页。没有错误。函数download被调用时没有任何问题,但是在调用之后它只显示空白页。

    如果我把密码

    return response()->下载(存储路径('app/files/gggusers.xlsx'));
    

    里面 function index()

    如果有人能向我解释原因,我真的很感激。这是某种bug,还是PHP/Laravel的预期行为。因为这个问题浪费了几个小时。

        2
  •  0
  •   user931018    5 年前

    download() 对于调用函数, index() 索引()

    public function download(){
            return response()->download(storage_path('app/files/gggusers.xlsx'));
    }
    

    索引() 功能,但在 函数您不会将任何内容返回到浏览器。所以改变这个:

    public function index(){
            $this->download();
    }
    

    为此:

    public function index(){
            return $this->download();
    }
    

    将按您的预期将文件返回到浏览器选项卡。

    这是正确的方法。