没有命名空间的类 yii yii\base yii\behaviors yii\caching yii\captcha yii\console yii\console\controllers yii\console\widgets yii\data yii\db yii\db\conditions yii\db\cubrid yii\db\cubrid\conditions yii\db\mssql yii\db\mssql\conditions yii\db\mysql yii\db\oci yii\db\oci\conditions yii\db\pgsql yii\db\sqlite yii\db\sqlite\conditions yii\di yii\filters yii\filters\auth yii\grid yii\helpers yii\i18n yii\log yii\mail yii\mutex yii\rbac yii\rest yii\test yii\validators yii\web yii\widgets

Class yii\web\Response

继承yii\web\Response » yii\base\Response » yii\base\Component » yii\base\BaseObject
实现yii\base\Configurable
可用版本自2.0
源码 https://github.com/yiichina/yii2/blob/api/framework/web/Response.php

The web Response class represents an HTTP response.

It holds the $headers, $cookies and $content that is to be sent to the client. It also controls the HTTP status code.

Response is configured as an application component in yii\web\Application by default. You can access that instance via Yii::$app->response.

You can modify its configuration by adding an array to your application config under components as it is shown in the following example:

'response' => [
    'format' => yii\web\Response::FORMAT_JSON,
    'charset' => 'UTF-8',
    // ...
]

For more details and usage information on Response, see the guide article on responses.

公共属性

隐藏继承的属性

属性类型描述被定义在
$acceptMimeType string The MIME type (e.g. application/json) from the request ACCEPT header chosen for this response. yii\web\Response
$acceptParams array The parameters (e.g. `['q' => 1, 'version' => '1. yii\web\Response
$behaviors yii\base\Behavior[] List of behaviors attached to this component yii\base\Component
$charset string The charset of the text response. yii\web\Response
$content string The response content. yii\web\Response
$cookies yii\web\CookieCollection The cookie collection. yii\web\Response
$data mixed The original response data. yii\web\Response
$downloadHeaders string The attachment file name yii\web\Response
$exitStatus integer 退出状态码。 退出状态码应在 0 到 254 范围内。 状态 0 表示程序成功终止。 yii\base\Response
$format string The response format. yii\web\Response
$formatters array The formatters for converting data into the response content of the specified $format. yii\web\Response
$headers yii\web\HeaderCollection The header collection yii\web\Response
$httpStatuses array List of HTTP status codes and the corresponding texts yii\web\Response
$isClientError boolean Whether this response indicates a client error yii\web\Response
$isEmpty boolean Whether this response is empty yii\web\Response
$isForbidden boolean Whether this response indicates the current request is forbidden yii\web\Response
$isInformational boolean Whether this response is informational yii\web\Response
$isInvalid boolean Whether this response has a valid $statusCode. yii\web\Response
$isNotFound boolean Whether this response indicates the currently requested resource is not found yii\web\Response
$isOk boolean Whether this response is OK yii\web\Response
$isRedirection boolean Whether this response is a redirection yii\web\Response
$isSent boolean Whether the response has been sent. yii\web\Response
$isServerError boolean Whether this response indicates a server error yii\web\Response
$isSuccessful boolean Whether this response is successful yii\web\Response
$statusCode integer The HTTP status code to send with the response. yii\web\Response
$statusCodeByException Exception|Error The exception object. yii\web\Response
$statusText string The HTTP status description that comes together with the status code. yii\web\Response
$stream resource|array The stream to be sent. yii\web\Response
$version string The version of the HTTP protocol to use. yii\web\Response

公共方法

隐藏继承的方法

方法描述被定义在
__call() Calls the named method which is not a class method. yii\base\Component
__clone() This method is called after the object is created by cloning an existing one. yii\base\Component
__construct() Constructor. yii\base\BaseObject
__get() Returns the value of a component property. yii\base\Component
__isset() Checks if a property is set, i.e. defined and not null. yii\base\Component
__set() Sets the value of a component property. yii\base\Component
__unset() Sets a component property to be null. yii\base\Component
attachBehavior() Attaches a behavior to this component. yii\base\Component
attachBehaviors() Attaches a list of behaviors to the component. yii\base\Component
behaviors() Returns a list of behaviors that this component should behave as. yii\base\Component
canGetProperty() Returns a value indicating whether a property can be read. yii\base\Component
canSetProperty() Returns a value indicating whether a property can be set. yii\base\Component
className() Returns the fully qualified name of this class. yii\base\BaseObject
clear() Clears the headers, cookies, content, status code of the response. yii\web\Response
clearOutputBuffers() 清空所有现有输出缓冲区。 yii\base\Response
detachBehavior() Detaches a behavior from the component. yii\base\Component
detachBehaviors() Detaches all behaviors from the component. yii\base\Component
ensureBehaviors() Makes sure that the behaviors declared in behaviors() are attached to this component. yii\base\Component
getBehavior() Returns the named behavior object. yii\base\Component
getBehaviors() Returns all behaviors attached to this component. yii\base\Component
getCookies() Returns the cookie collection. yii\web\Response
getHeaders() Returns the header collection. yii\web\Response
getIsClientError() yii\web\Response
getIsEmpty() yii\web\Response
getIsForbidden() yii\web\Response
getIsInformational() yii\web\Response
getIsInvalid() yii\web\Response
getIsNotFound() yii\web\Response
getIsOk() yii\web\Response
getIsRedirection() yii\web\Response
getIsServerError() yii\web\Response
getIsSuccessful() yii\web\Response
getStatusCode() yii\web\Response
hasEventHandlers() Returns a value indicating whether there is any handler attached to the named event. yii\base\Component
hasMethod() Returns a value indicating whether a method is defined. yii\base\Component
hasProperty() Returns a value indicating whether a property is defined for this component. yii\base\Component
init() Initializes this component. yii\web\Response
off() Detaches an existing event handler from this component. yii\base\Component
on() Attaches an event handler to an event. yii\base\Component
redirect() Redirects the browser to the specified URL. yii\web\Response
refresh() Refreshes the current page. yii\web\Response
send() Sends the response to the client. yii\web\Response
sendContentAsFile() Sends the specified content as a file to the browser. yii\web\Response
sendFile() Sends a file to the browser. yii\web\Response
sendStreamAsFile() Sends the specified stream as a file to the browser. yii\web\Response
setDownloadHeaders() Sets a default set of HTTP headers for file downloading purpose. yii\web\Response
setStatusCode() Sets the response status code. yii\web\Response
setStatusCodeByException() Sets the response status code based on the exception. yii\web\Response
trigger() Triggers an event. yii\base\Component
xSendFile() Sends existing file to a browser as a download using x-sendfile. yii\web\Response

受保护的方法

隐藏继承的方法

方法描述被定义在
defaultFormatters() yii\web\Response
getDispositionHeaderValue() Returns Content-Disposition header value that is safe to use with both old and new browsers. yii\web\Response
getHttpRange() Determines the HTTP range given in the request. yii\web\Response
prepare() Prepares for sending the response. yii\web\Response
sendContent() Sends the response content to the client. yii\web\Response
sendCookies() Sends the cookies to the client. yii\web\Response
sendHeaders() Sends the response headers to the client. yii\web\Response

Events

隐藏继承的事件

事件类型描述被定义在
EVENT_AFTER_PREPARE \yii\web\ResponseEvent An event that is triggered right after prepare() is called in send(). yii\web\Response
EVENT_AFTER_SEND \yii\web\ResponseEvent An event that is triggered at the end of send(). yii\web\Response
EVENT_BEFORE_SEND \yii\web\ResponseEvent An event that is triggered at the beginning of send(). yii\web\Response

常量

隐藏继承的常量

常量描述被定义在
FORMAT_HTML 'html' yii\web\Response
FORMAT_JSON 'json' yii\web\Response
FORMAT_JSONP 'jsonp' yii\web\Response
FORMAT_RAW 'raw' yii\web\Response
FORMAT_XML 'xml' yii\web\Response

属性详情

$acceptMimeType 公共 属性

The MIME type (e.g. application/json) from the request ACCEPT header chosen for this response. This property is mainly set by yii\filters\ContentNegotiator.

public string $acceptMimeType null
$acceptParams 公共 属性

The parameters (e.g. ['q' => 1, 'version' => '1.0']) associated with the chosen MIME type. This is a list of name-value pairs associated with $acceptMimeType from the ACCEPT HTTP header. This property is mainly set by yii\filters\ContentNegotiator.

public array $acceptParams = []
$charset 公共 属性

The charset of the text response. If not set, it will use the value of yii\web\Application::$charset.

public string $charset null
$content 公共 属性

The response content. When $data is not null, it will be converted into $content according to $format when the response is being sent out.

参见 $data.

public string $content null
$cookies 公共 只读 属性

The cookie collection.

$data 公共 属性

The original response data. When this is not null, it will be converted into $content according to $format when the response is being sent out.

参见 $content.

public mixed $data null
$downloadHeaders 公共 只写 属性

The attachment file name

public $this setDownloadHeaders ( $attachmentName, $mimeType null, $inline false, $contentLength null )
$format 公共 属性

The response format. This determines how to convert $data into $content when the latter is not set. The value of this property must be one of the keys declared in the $formatters array. By default, the following formats are supported:

  • FORMAT_RAW: the data will be treated as the response content without any conversion. No extra HTTP header will be added.
  • FORMAT_HTML: the data will be treated as the response content without any conversion. The "Content-Type" header will set as "text/html".
  • FORMAT_JSON: the data will be converted into JSON format, and the "Content-Type" header will be set as "application/json".
  • FORMAT_JSONP: the data will be converted into JSONP format, and the "Content-Type" header will be set as "text/javascript". Note that in this case $data must be an array with "data" and "callback" elements. The former refers to the actual data to be sent, while the latter refers to the name of the JavaScript callback.
  • FORMAT_XML: the data will be converted into XML format. Please refer to yii\web\XmlResponseFormatter for more details.

You may customize the formatting process or support additional formats by configuring $formatters.

参见 $formatters.

public string $format self::FORMAT_HTML
$formatters 公共 属性

The formatters for converting data into the response content of the specified $format. The array keys are the format names, and the array values are the corresponding configurations for creating the formatter objects.

参见:

public array $formatters = []
$headers 公共 只读 属性

The header collection

$httpStatuses 公共 静态 属性

List of HTTP status codes and the corresponding texts

public static array $httpStatuses = [100 => 'Continue'101 => 'Switching Protocols'102 => 'Processing'118 => 'Connection timed out'200 => 'OK'201 => 'Created'202 => 'Accepted'203 => 'Non-Authoritative'204 => 'No Content'205 => 'Reset Content'206 => 'Partial Content'207 => 'Multi-Status'208 => 'Already Reported'210 => 'Content Different'226 => 'IM Used'300 => 'Multiple Choices'301 => 'Moved Permanently'302 => 'Found'303 => 'See Other'304 => 'Not Modified'305 => 'Use Proxy'306 => 'Reserved'307 => 'Temporary Redirect'308 => 'Permanent Redirect'310 => 'Too many Redirect'400 => 'Bad Request'401 => 'Unauthorized'402 => 'Payment Required'403 => 'Forbidden'404 => 'Not Found'405 => 'Method Not Allowed'406 => 'Not Acceptable'407 => 'Proxy Authentication Required'408 => 'Request Time-out'409 => 'Conflict'410 => 'Gone'411 => 'Length Required'412 => 'Precondition Failed'413 => 'Request Entity Too Large'414 => 'Request-URI Too Long'415 => 'Unsupported Media Type'416 => 'Requested range unsatisfiable'417 => 'Expectation failed'418 => 'I\'m a teapot'421 => 'Misdirected Request'422 => 'Unprocessable entity'423 => 'Locked'424 => 'Method failure'425 => 'Unordered Collection'426 => 'Upgrade Required'428 => 'Precondition Required'429 => 'Too Many Requests'431 => 'Request Header Fields Too Large'449 => 'Retry With'450 => 'Blocked by Windows Parental Controls'451 => 'Unavailable For Legal Reasons'500 => 'Internal Server Error'501 => 'Not Implemented'502 => 'Bad Gateway or Proxy Error'503 => 'Service Unavailable'504 => 'Gateway Time-out'505 => 'HTTP Version not supported'507 => 'Insufficient storage'508 => 'Loop Detected'509 => 'Bandwidth Limit Exceeded'510 => 'Not Extended'511 => 'Network Authentication Required']
$isClientError 公共 只读 属性

Whether this response indicates a client error

$isEmpty 公共 只读 属性

Whether this response is empty

public boolean getIsEmpty ( )
$isForbidden 公共 只读 属性

Whether this response indicates the current request is forbidden

$isInformational 公共 只读 属性

Whether this response is informational

$isInvalid 公共 只读 属性

Whether this response has a valid $statusCode.

$isNotFound 公共 只读 属性

Whether this response indicates the currently requested resource is not found

$isOk 公共 只读 属性

Whether this response is OK

public boolean getIsOk ( )
$isRedirection 公共 只读 属性

Whether this response is a redirection

$isSent 公共 属性

Whether the response has been sent. If this is true, calling send() will do nothing.

public boolean $isSent false
$isServerError 公共 只读 属性

Whether this response indicates a server error

$isSuccessful 公共 只读 属性

Whether this response is successful

$statusCode 公共 属性

The HTTP status code to send with the response.

public integer getStatusCode ( )
public $this setStatusCode ( $value, $text null )
$statusCodeByException 公共 只写 属性

The exception object.

$statusText 公共 属性

The HTTP status description that comes together with the status code.

参见 $httpStatuses.

public string $statusText 'OK'
$stream 公共 属性

The stream to be sent. This can be a stream handle or an array of stream handle, the begin position and the end position. Note that when this property is set, the $data and $content properties will be ignored by send().

public resource|array $stream null
$version 公共 属性

The version of the HTTP protocol to use. If not set, it will be determined via $_SERVER['SERVER_PROTOCOL'], or '1.1' if that is not available.

public string $version null

方法详情

clear() 公共 方法

Clears the headers, cookies, content, status code of the response.

public void clear()
defaultFormatters() 受保护 方法

protected array defaultFormatters()
return array

The formatters that are supported by default

getCookies() 公共 方法

Returns the cookie collection.

Through the returned cookie collection, you add or remove cookies as follows,

// add a cookie
$response->cookies->add(new Cookie([
    'name' => $name,
    'value' => $value,
]);

// remove a cookie
$response->cookies->remove('name');
// alternatively
unset($response->cookies['name']);
public yii\web\CookieCollection getCookies()
return yii\web\CookieCollection

The cookie collection.

getDispositionHeaderValue() 受保护 方法 (自版本 2.0.10 可用)

Returns Content-Disposition header value that is safe to use with both old and new browsers.

Fallback name:

  • Causes issues if contains non-ASCII characters with codes less than 32 or more than 126.
  • Causes issues if contains urlencoded characters (starting with %) or % character. Some browsers interpret filename="X" as urlencoded name, some don't.
  • Causes issues if contains path separator characters such as \ or /.
  • Since value is wrapped with ", it should be escaped as \".
  • Since input could contain non-ASCII characters, fallback is obtained by transliteration.

UTF name:

  • Causes issues if contains path separator characters such as \ or /.
  • Should be urlencoded since headers are ASCII-only.
  • Could be omitted if it exactly matches fallback name.
protected string getDispositionHeaderValue($disposition, $attachmentName)
$disposition string
$attachmentName string
getHeaders() 公共 方法

Returns the header collection.

The header collection contains the currently registered HTTP headers.

public yii\web\HeaderCollection getHeaders()
return yii\web\HeaderCollection

The header collection

getHttpRange() 受保护 方法

Determines the HTTP range given in the request.

protected array|boolean getHttpRange($fileSize)
$fileSize integer

The size of the file that will be used to validate the requested HTTP range.

return array|boolean

The range (begin, end), or false if the range request is invalid.

getIsClientError() 公共 方法

public boolean getIsClientError()
return boolean

Whether this response indicates a client error

getIsEmpty() 公共 方法

public boolean getIsEmpty()
return boolean

Whether this response is empty

getIsForbidden() 公共 方法

public boolean getIsForbidden()
return boolean

Whether this response indicates the current request is forbidden

getIsInformational() 公共 方法

public boolean getIsInformational()
return boolean

Whether this response is informational

getIsInvalid() 公共 方法

public boolean getIsInvalid()
return boolean

Whether this response has a valid $statusCode.

getIsNotFound() 公共 方法

public boolean getIsNotFound()
return boolean

Whether this response indicates the currently requested resource is not found

getIsOk() 公共 方法

public boolean getIsOk()
return boolean

Whether this response is OK

getIsRedirection() 公共 方法

public boolean getIsRedirection()
return boolean

Whether this response is a redirection

getIsServerError() 公共 方法

public boolean getIsServerError()
return boolean

Whether this response indicates a server error

getIsSuccessful() 公共 方法

public boolean getIsSuccessful()
return boolean

Whether this response is successful

getStatusCode() 公共 方法

public integer getStatusCode()
return integer

The HTTP status code to send with the response.

init() 公共 方法

Initializes this component.

public void init()
prepare() 受保护 方法

Prepares for sending the response.

The default implementation will convert $data into $content and set headers accordingly.

protected void prepare()
throws yii\base\InvalidConfigException

if the formatter for the specified format is invalid or $format is not supported

redirect() 公共 方法

Redirects the browser to the specified URL.

This method adds a "Location" header to the current response. Note that it does not send out the header until send() is called. In a controller action you may use this method as follows:

return Yii::$app->getResponse()->redirect($url);

In other places, if you want to send out the "Location" header immediately, you should use the following code:

Yii::$app->getResponse()->redirect($url)->send();
return;

In AJAX mode, this normally will not work as expected unless there are some client-side JavaScript code handling the redirection. To help achieve this goal, this method will send out a "X-Redirect" header instead of "Location".

If you use the "yii" JavaScript module, it will handle the AJAX redirection as described above. Otherwise, you should write the following JavaScript code to handle the redirection:

$document.ajaxComplete(function (event, xhr, settings) {
    var url = xhr && xhr.getResponseHeader('X-Redirect');
    if (url) {
        window.location = url;
    }
});
public $this redirect($url, $statusCode 302, $checkAjax true)
$url string|array

The URL to be redirected to. This can be in one of the following formats:

  • a string representing a URL (e.g. "http://example.com")
  • a string representing a URL alias (e.g. "@example.com")
  • an array in the format of [$route, ...name-value pairs...] (e.g. ['site/index', 'ref' => 1]). Note that the route is with respect to the whole application, instead of relative to a controller or module. yii\helpers\Url::to() will be used to convert the array into a URL.

Any relative URL that starts with a single forward slash "/" will be converted into an absolute one by prepending it with the host info of the current request.

$statusCode integer

The HTTP status code. Defaults to 302. See https://tools.ietf.org/html/rfc2616#section-10 for details about HTTP status code

$checkAjax boolean

Whether to specially handle AJAX (and PJAX) requests. Defaults to true, meaning if the current request is an AJAX or PJAX request, then calling this method will cause the browser to redirect to the given URL. If this is false, a Location header will be sent, which when received as an AJAX/PJAX response, may NOT cause browser redirection. Takes effect only when request header X-Ie-Redirect-Compatibility is absent.

return $this

The response object itself

refresh() 公共 方法

Refreshes the current page.

The effect of this method call is the same as the user pressing the refresh button of his browser (without re-posting data).

In a controller action you may use this method like this:

return Yii::$app->getResponse()->refresh();
public yii\web\Response refresh($anchor '')
$anchor string

The anchor that should be appended to the redirection URL. Defaults to empty. Make sure the anchor starts with '#' if you want to specify it.

return yii\web\Response

The response object itself

send() 公共 方法

Sends the response to the client.

public void send()
sendContent() 受保护 方法

Sends the response content to the client.

protected void sendContent()
sendContentAsFile() 公共 方法

Sends the specified content as a file to the browser.

Note that this method only prepares the response for file sending. The file is not sent until send() is called explicitly or implicitly. The latter is done after you return from a controller action.

参见 sendFile() for an example implementation.

public $this sendContentAsFile($content, $attachmentName, $options = [])
$content string

The content to be sent. The existing $content will be discarded.

$attachmentName string

The file name shown to the user.

$options array

Additional options for sending the file. The following options are supported:

  • mimeType: the MIME type of the content. Defaults to 'application/octet-stream'.
  • inline: boolean, whether the browser should open the file within the browser window. Defaults to false, meaning a download dialog will pop up.
return $this

The response object itself

throws yii\web\RangeNotSatisfiableHttpException

if the requested range is not satisfiable

sendCookies() 受保护 方法

Sends the cookies to the client.

protected void sendCookies()
sendFile() 公共 方法

Sends a file to the browser.

Note that this method only prepares the response for file sending. The file is not sent until send() is called explicitly or implicitly. The latter is done after you return from a controller action.

The following is an example implementation of a controller action that allows requesting files from a directory that is not accessible from web:

public function actionFile($filename)
{
    $storagePath = Yii::getAlias('@app/files');

    // check filename for allowed chars (do not allow ../ to avoid security issue: downloading arbitrary files)
    if (!preg_match('/^[a-z0-9]+\.[a-z0-9]+$/i', $filename) || !is_file("$storagePath/$filename")) {
        throw new \yii\web\NotFoundHttpException('The file does not exists.');
    }
    return Yii::$app->response->sendFile("$storagePath/$filename", $filename);
}

参见:

public $this sendFile($filePath, $attachmentName null, $options = [])
$filePath string

The path of the file to be sent.

$attachmentName string

The file name shown to the user. If null, it will be determined from $filePath.

$options array

Additional options for sending the file. The following options are supported:

  • mimeType: the MIME type of the content. If not set, it will be guessed based on $filePath
  • inline: boolean, whether the browser should open the file within the browser window. Defaults to false, meaning a download dialog will pop up.
return $this

The response object itself

sendHeaders() 受保护 方法

Sends the response headers to the client.

protected void sendHeaders()
sendStreamAsFile() 公共 方法

Sends the specified stream as a file to the browser.

Note that this method only prepares the response for file sending. The file is not sent until send() is called explicitly or implicitly. The latter is done after you return from a controller action.

参见 sendFile() for an example implementation.

public $this sendStreamAsFile($handle, $attachmentName, $options = [])
$handle resource

The handle of the stream to be sent.

$attachmentName string

The file name shown to the user.

$options array

Additional options for sending the file. The following options are supported:

  • mimeType: the MIME type of the content. Defaults to 'application/octet-stream'.
  • inline: boolean, whether the browser should open the file within the browser window. Defaults to false, meaning a download dialog will pop up.
  • fileSize: the size of the content to stream this is useful when size of the content is known and the content is not seekable. Defaults to content size using ftell(). This option is available since version 2.0.4.
return $this

The response object itself

throws yii\web\RangeNotSatisfiableHttpException

if the requested range is not satisfiable

setDownloadHeaders() 公共 方法

Sets a default set of HTTP headers for file downloading purpose.

public $this setDownloadHeaders($attachmentName, $mimeType null, $inline false, $contentLength null)
$attachmentName string

The attachment file name

$mimeType string

The MIME type for the response. If null, Content-Type header will NOT be set.

$inline boolean

Whether the browser should open the file within the browser window. Defaults to false, meaning a download dialog will pop up.

$contentLength integer

The byte length of the file being downloaded. If null, Content-Length header will NOT be set.

return $this

The response object itself

setStatusCode() 公共 方法

Sets the response status code.

This method will set the corresponding status text if $text is null.

public $this setStatusCode($value, $text null)
$value integer

The status code

$text string

The status text. If not set, it will be set automatically based on the status code.

return $this

The response object itself

throws yii\base\InvalidArgumentException

if the status code is invalid.

setStatusCodeByException() 公共 方法 (自版本 2.0.12 可用)

Sets the response status code based on the exception.

public $this setStatusCodeByException($e)
$e Exception|Error

The exception object.

return $this

The response object itself

throws yii\base\InvalidArgumentException

if the status code is invalid.

xSendFile() 公共 方法

Sends existing file to a browser as a download using x-sendfile.

X-Sendfile is a feature allowing a web application to redirect the request for a file to the webserver that in turn processes the request, this way eliminating the need to perform tasks like reading the file and sending it to the user. When dealing with a lot of files (or very big files) this can lead to a great increase in performance as the web application is allowed to terminate earlier while the webserver is handling the request.

The request is sent to the server through a special non-standard HTTP-header. When the web server encounters the presence of such header it will discard all output and send the file specified by that header using web server internals including all optimizations like caching-headers.

As this header directive is non-standard different directives exists for different web servers applications:

So for this method to work the X-SENDFILE option/module should be enabled by the web server and a proper xHeader should be sent.

Note

This option allows to download files that are not under web folders, and even files that are otherwise protected (deny from all) like .htaccess.

Side effects

If this option is disabled by the web server, when this method is called a download configuration dialog will open but the downloaded file will have 0 bytes.

Known issues

There is a Bug with Internet Explorer 6, 7 and 8 when X-SENDFILE is used over an SSL connection, it will show an error message like this: "Internet Explorer was not able to open this Internet site. The requested site is either unavailable or cannot be found.". You can work around this problem by removing the Pragma-header.

Example

Yii::$app->response->xSendFile('/home/user/Pictures/picture1.jpg');

参见 sendFile().

public $this xSendFile($filePath, $attachmentName null, $options = [])
$filePath string

File name with full path

$attachmentName string

File name shown to the user. If null, it will be determined from $filePath.

$options array

Additional options for sending the file. The following options are supported:

  • mimeType: the MIME type of the content. If not set, it will be guessed based on $filePath
  • inline: boolean, whether the browser should open the file within the browser window. Defaults to false, meaning a download dialog will pop up.
  • xHeader: string, the name of the x-sendfile header. Defaults to "X-Sendfile".
return $this

The response object itself

事件详情

EVENT_AFTER_PREPARE event of type \yii\web\ResponseEvent

An event that is triggered right after prepare() is called in send(). You may respond to this event to filter the response content before it is sent to the client.

EVENT_AFTER_SEND event of type \yii\web\ResponseEvent

An event that is triggered at the end of send().

EVENT_BEFORE_SEND event of type \yii\web\ResponseEvent

An event that is triggered at the beginning of send().