加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP REST下载文件

发布时间:2020-12-13 21:52:09 所属栏目:PHP教程 来源:网络整理
导读:我有一个像这样的功能的web服务 $app-get('/downloadPdf',function () use($app) { $log = 'example.pdf'; $res = $app-response(); $res['Content-Description'] = 'File Transfer'; $res['Content-Type'] = 'application/octet-stream'; $res['Content-Dis
我有一个像这样的功能的web服务

$app->get('/downloadPdf',function () use($app) 
{
    $log = 'example.pdf';
    $res = $app->response();
    $res['Content-Description'] = 'File Transfer';
    $res['Content-Type'] = 'application/octet-stream';
    $res['Content-Disposition'] ='attachment; filename=' . basename($log);
    $res['Content-Transfer-Encoding'] = 'binary';
    $res['Expires'] = '0';
    $res['Cache-Control'] = 'must-revalidate';
    $res['Pragma'] = 'public';
    $res['Content-Length'] = filesize($log);
    readfile($log);
});

使用Advanced Rest Client进行测试工作正常..

问题是..如何从我的客户端调用所有标题等.

要指定更多.我知道有很多关于如何通过将其url插入curlopt_url以及文件的完整地址来下载特定文件的示例.我想要的是让webservice决定返回哪个文件…

谢谢

解决方法

从来没有得到答案..所以!!!

这就是我的工作方式….

服务功能如下所示

$app->post('/downloadReport','authenticate',function() use ($app) 
{
verifyRequiredParams(array('reportId'));

$body = $app->request()->getBody();
$params_str = urldecode($body);     
$input = json_decode($params_str,true);             

$report_id = $input['reportId'];    
$db = new DbHandler();    
$db->getReport($report_id);

$path = $db->getReportPdfPath($report_id);

$res = $app->response();
$res['Content-Description'] = 'File Transfer';
$res['Content-Type'] = 'application/octet-stream';
$res['Content-Disposition'] ='attachment; filename=' . basename($path);
$res['Content-Transfer-Encoding'] = 'binary';
$res['Expires'] = '0';
$res['Cache-Control'] = 'must-revalidate';
$res['Pragma'] = 'public';
$res['Content-Length'] = filesize($path);
readfile($path);   

});

称为这样的功能:

public function downloadReport($api_key,$id)
{

    $curl_post_data = array('reportId' => $id);

    $headers = array('Content-type: application/json','Authorization: '.$api_key,);
    $fp = fopen (dirname(__FILE__) . '/localfile.tmp','w+');//This is the file where we save the    information
    $curl = curl_init(DONWLOAD_REPORT);
    curl_setopt($curl,CURLOPT_HTTPHEADER,$headers);
    curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($curl,CURLOPT_POST,CURLOPT_POSTFIELDS,json_encode($curl_post_data));
    curl_setopt($curl,CURLOPT_USERPWD,$api_key);
    $file = curl_exec($curl);

    if ($file === false) 
    {
        $info = curl_getinfo($curl);
        curl_close($curl);
        die('error occured during curl exec. Additioanl info: ' . var_export($info));
    }

    curl_close($curl);

    header('Content-type: ' . 'application/octet-stream');
    header('Content-Disposition: ' . 'attachment; filename=report.pdf');
    echo $file;        
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读