从Slim Framework 2.4下载文件 [英] Download file from Slim Framework 2.4

查看:95
本文介绍了从Slim Framework 2.4下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让用户在Slim php框架中下载文件.

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

该文件的预期用途是:

http://api.test.com/item/123.json < ;-返回带有数据的json字符串

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

http://api.test.com/item/123.pdf < ;-下载具有人类可读数据表示形式的pdf文件

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

我有生成PDF的代码,但是我需要让Slim发送正确的标头,以便下载文件.

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;

以下是我当前的(无效的)Slim代码,其中声明的标头未发送到浏览器.相反,我得到了text/html. (请注意,此示例仅包含一个标头,我还测试了是否有其他标头操作会产生任何效果,但事实并非如此).稍后会添加json/pdf/xml的切换用例.

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();

但是$ app-> response-> setBody($ f-> data)可以正常工作.

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

推荐答案

问题已解决.原来是一个包含空格的php类.我猜这弄乱了标题.

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.

在Slim函数中设置标题的有效解决方案;

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();
?>

已更新:这是我用来让用户下载PDF的标题:

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);

这篇关于从Slim Framework 2.4下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆