可以通过以下代码完成同样的工作:
header('Content-Type:image/jpeg');
readfile('a.jpg');
但现在我对Yii2的\yii\web\Response.
我感到困惑的是:
创建一个控制器和动作以提供图片
见下文
class ServerController extends \yii\web\Controller
{
public function actionIndex($name)
{
// how to response
}
}
访问http://example.com/index.php?r=server/index&name=foo.jpg
感谢您的回答!
答案 0 :(得分:15)
最后,我按照以下代码进行了操作:
$response = Yii::$app->getResponse();
$response->headers->set('Content-Type', 'image/jpeg');
$response->format = Response::FORMAT_RAW;
if ( !is_resource($response->stream = fopen($imgFullPath, 'r')) ) {
throw new \yii\web\ServerErrorHttpException('file access failed: permission deny');
}
return $response->send();
答案 1 :(得分:5)
,您可以从行yii\web\Response中返回响应对象。所以你可以回复自己的回复。
例如yii2中的显示图像:
public function actionIndex() {
\Yii::$app->response->format = yii\web\Response::FORMAT_RAW;
\Yii::$app->response->headers->add('content-type','image/png');
\Yii::$app->response->data = file_get_contents('file.png');
return \Yii::$app->response;
}
FORMAT_RAW:数据将被视为响应内容而不进行任何转换。不会添加额外的HTTP标头。
答案 2 :(得分:4)
Yii2已经为sending files提供了内置功能。这样您就不需要设置响应格式,并且会自动检测内容类型(如果您愿意,可以覆盖它):
function actionDownload()
{
$imgFullPath = 'picture.jpg';
return Yii::$app->response->sendFile($imgFullPath);
}
...
如果该文件仅为当前下载操作临时创建,您可以使用AFTER_SEND
事件删除该文件:
function actionDownload()
{
$imgFullPath = 'picture.jpg';
return Yii::$app->response
->sendFile($imgFullPath)
->on(\yii\web\Response::EVENT_AFTER_SEND, function($event) {
unlink($event->data);
}, $imgFullPath);
}
答案 3 :(得分:3)
$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
答案 4 :(得分:2)
Yii2方式:
Yii::$app->response->setDownloadHeaders($filename);