yii2:如何响应图像并让浏览器显示它? [英] yii2: how to response image and let browser show it?
问题描述
同样的工作可以通过以下代码完成:
the same work can be done by follow code:
header('Content-Type:image/jpeg');
readfile('a.jpg');
但现在我真的被 Yii2 的 \yii\web\Response 搞糊涂了.
but now I really confused by Yii2's \yii\web\Response.
我的困惑是这样的:
创建一个控制器和动作来提供图片
create a controller and action to provide picture
见下文
class ServerController extends \yii\web\Controller
{
public function actionIndex($name)
{
// how to response
}
}
访问http://example.com/index.php?r=server/index&name=foo.jpg
感谢您的回答!
推荐答案
我就是这样做的.我添加了另一个功能只是为了设置标题.您也可以在助手中移动此功能:
I do it like this. I have added another function just for setting the headers. You can move this function in a helper too:
$this->setHttpHeaders('csv', 'filename', 'text/plain');
/**
* Sets the HTTP headers needed by file download action.
*/
protected function setHttpHeaders($type, $name, $mime, $encoding = 'utf-8')
{
Yii::$app->response->format = Response::FORMAT_RAW;
if (strstr($_SERVER["HTTP_USER_AGENT"], "MSIE") == false) {
header("Cache-Control: no-cache");
header("Pragma: no-cache");
} else {
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Pragma: public");
}
header("Expires: Sat, 26 Jul 1979 05:00:00 GMT");
header("Content-Encoding: {$encoding}");
header("Content-Type: {$mime}; charset={$encoding}");
header("Content-Disposition: attachment; filename={$name}.{$type}");
header("Cache-Control: max-age=0");
}
我也找到了 yii2 是怎么做的,看这里(滚动到底部)https://github.com/yiisoft/yii2/blob/48ec791e4aca792435ef1fdce80ee7f6ef365c5c/framework/captcha/CaptchaAction.php
I also found how yii2 does it, take a look here (scroll to the bottom) https://github.com/yiisoft/yii2/blob/48ec791e4aca792435ef1fdce80ee7f6ef365c5c/framework/captcha/CaptchaAction.php
这篇关于yii2:如何响应图像并让浏览器显示它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!