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

streamdownload方法返回空响应,未下载文件

  •  0
  • superfive33  · 技术社区  · 6 年前

    我的控制器中有以下方法,在使用post调用路由'/download/'时触发:

    public function download(Request $request) {
        return response()->streamDownload( function () use ( $request ) {
            return $request->content;
        }, 'page.html' );
    }
    

    我从javascript应用程序通过ajax调用这个路由。

    问题是文件下载不起作用。响应是空的。但是,响应代码是200,没有错误…

    怎么了?
    谢谢

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

    好吧,我做错了。我的解决方案是:

    // @param url : the url of the file on server
    function downloadHTML (url) {
        url = new URL(url);
        return axios({
            // I've created a GET API route on my server using the pathname of the file url, which returns the content of the file
            url: url.origin + '/api' + url.pathname,
            method: 'GET',
            responseType: 'blob',
        }).then((response) => {
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', 'file.pdf'); //or any other extension
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        });
    }