doukunsan5553 2014-04-07 11:47
浏览 96
已采纳

从Slim Framework 2.4下载文件

I am trying to let the user download a file in the Slim php framework.

The intended use is that the file will be:

http://api.test.com/item/123.json <- returns json string with data

http://api.test.com/item/123.pdf <- download pdf-file with human-readable presentation of data

I have the code producing the PDF, but what I need is to make Slim send the correct headers so the file will be downloaded.

This is the following code I have (working) for the existing system:

header("Pragma: public");
header('Content-disposition: attachment; filename='.$f->name);
header('Content-type: ' .$f->type);
header('Content-Transfer-Encoding: binary');
echo $f->data;

Following is my current (non-working) Slim-code where the headers I declare is not sent to the browser. Instead I get text/html. (Note that this example only contains one header, I have also tested to see if any other header manipulation would cause any effect, but it haven't). The switch-case of json/pdf/xml will be added later on.

R::setup();    
$app = new \Slim\Slim();
$app->get('/item', function() use ($app) {
    $f = R::load('file', 123);
    $app->response->headers->set("Content-Type", "application/pdf"); //$f->type
    $app->response->setBody($f->data);

 });

$app->run();

The $app->response->setBody($f->data) however works fine.

  • 写回答

1条回答 默认 最新

  • donglian5309 2014-04-08 09:40
    关注

    Problem solved. Turned out to be a included php class with whitespace in it. This messed up the headers i guess.

    Solved by creating a new, empty project and include step by step until the bad class showed.

    Working solution for setting headers inside a Slim function;

    <?php
    
    require 'vendor/autoload.php';
    $app = new \Slim\Slim();
    
    $app->get('/foo', function () use ($app) {
        $app->response->headers->set('Content-Type', "application/pdf");
        $app->response->setBody("foo");
    });
    
    $app->run();
    ?>
    

    Updated: This is the headers I use to let a user download a PDF:

    $app->response->headers->set('Content-Type', $f->type);
    $app->response->headers->set('Pragma', "public");
    $app->response->headers->set('Content-disposition:', 'attachment; filename=' . $f->name);
    $app->response->headers->set('Content-Transfer-Encoding', 'binary');
    $app->response->headers->set('Content-Length', $f->size);
    $app->response->setBody($f->data);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题