为什么需要两个请求来传输文件?

时间:2018-06-22 23:27:59

标签: php laravel

我在下面使用此方法从API服务器下载文件。但是它不能正常工作,当用户单击调用getFile()方法的按钮时,它首先出现在页面

  

试图获取非对象的属性

但是,如果用户单击浏览器的刷新按钮,则会下载文件。

因此看来,要生成该文件是必要的,请发送两个请求,并在第一个请求中出现

  

试图获取非对象的属性

第二次传输文件,第三次再次出现

  

试图获取非对象的属性

在API中表示,下载文件是异步操作,这意味着该文件可能无法立即准备就绪。我不知道问题是否可能是因为这个原因。

代码:

 public function getFile($regId){
        $client = new \GuzzleHttp\Client();

        $user = Auth::user();

        $registration = $user->registrations()->with(["proforma"])->where("id", $regId)->first();
        $proforma = $registration->proforma->proforma_number;

        $getProforma = $client->request('GET', 'https://...'.$proforma.'.json', [
            'query' => ['api_key' => '...'],
        ]);
        $response = $getProforma->getBody()->getContents();

        $url = null;
        if(!empty($response)) {
            $response = json_decode($response);

            $url = !empty($response->output->pdfUrl) ? $response->output->pdfUrl : '';
        }
        header("Location: $url");
    }

2 个答案:

答案 0 :(得分:0)

public function getFile($regId)
{
    $registration = auth()->user()->registrations()->with(["proforma"])->where("id", $regId)->first();
    $proforma = $registration->proforma->proforma_number;

    $getProforma = json_decode(file_get_contents('https://...' . $proforma . '.json?api_key=.....'));
    // $getProforma->output here was your problem so I advice you to: dd($getProforma);
    $url = ! empty(optional($getProforma->output)->pdfUrl) ? optional($getProforma->output)->pdfUrl : '/'; // it will redict home if it couldn't find the PDF URL

    return redirect($url);
}

答案 1 :(得分:0)

尝试使用Laravel的StreamDownload响应:

public function getFile($regId){
    $client = new \GuzzleHttp\Client();

    $user = Auth::user();

    $registration = $user->registrations()->with(["proforma"])->where("id", $regId)->first();
    $proforma = $registration->proforma->proforma_number;

    $getProforma = $client->request('GET', 'https://...'.$proforma.'.json', [
        'query' => ['api_key' => '...'],
    ]);
    $contents = $getProforma->getBody()->getContents();

    return response()->streamDownload(function () use ($contents) {
        echo $contents;
    }, 'filename.extension');
}