laravel响应流下载返回空文件

时间:2019-11-22 08:03:28

标签: php laravel-5 laravel-response

我有一个控制器方法,该方法接收用户的下载请求,并使用请求的主体参数调用REST API端点。

作为回报,

API发送文件。

我正在使用Guzzle发出API请求和laravel版本5.4

$response->getBody()->getContents();的内容为:

"""
request_id\ts_sku\tr_product_url\thuman_verdict\n
199\tSG-948\thttps://www.amazon.com/gp/offer-listing/B076CP7J4P?condition=new\tMatch\n
199\tZIB-601\thttps://www.amazon.com/gp/offer-listing/B07D9PN39C?condition=new\tMatch\n
199\tRCM-LG526\thttps://www.amazon.com/gp/offer-listing/B07FDJ3W7P?condition=new\tMatch\n
199\tGSI-335\thttps://www.amazon.com/gp/offer-listing/B07GNX1VSG?condition=new\tMatch\n
199\tZIB-489\thttps://www.amazon.com/gp/offer-listing/B07D9RCGXM?condition=new\tMatch\n
"""

同样从API收到的标头响应是:

Content-Type : ('text/tab-separated-values', none)
Content-Disposition : attachment; filename=/path/to/file1.tsv

我试图在控制器中接收此文件,并将响应作为流下载返回到用户的浏览器。

这里的控制器方法:

    $client = new Client(["base_uri" => $this->apiBaseUrl]);
    $url = 'download/filterdownload/';

    try {
        $response = $client->request('POST', $url, ['headers'=>['Content-Type' => 'application/json'], 'body'=>json_encode($filterArr)]);
        # $resArr = json_decode($response, true);
    } catch (\Exception $e) {
        return redirect()->back()->with('error', $e->getMessage());
    }

    if(!empty($resArr) && array_key_exists('response', $resArr))
        return redirect()->back()->with('error', $resArr['response']);

    # return response
    $file = $response->getBody()->getContents();

    $file_name = $filterArr['client_name'].'_'.Carbon::now()->toDateString().'.tsv';
    $headers = [
        'Content-Disposition' => 'attachment; filename='. $file_name. ';'
    ];
    return response()->stream(function () {
        $file;
    }, 200, $headers);

这将下载文件,但该文件为空。

1 个答案:

答案 0 :(得分:1)

也许有帮助:

 # return response
    $file = $response->getBody()->getContents();

    $file_name = $filterArr['client_name'].'_'.Carbon::now()->toDateString().'.tsv';
    $headers = [
        'Content-Disposition' => 'attachment; filename='. $file_name. ';'
    ];
    return response()->stream(function () use ($file)  { <-- edit
        $file;
    }, 200, $headers);