I have xml file and I want to send it in my api action by http-response with Content-Type=multipart/form-data
Now I'm using Content-Type=text/xml and my action looks like
\Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
$headers = \Yii::$app->response->headers;
$headers->add('Content-Type', 'text/xml');
$xml = file_get_contents($filePath);
return $xml;
But it is not exactly what I want. How can I change this response to Content-Type=multipart/form-data ?
You can change the Content-Type
for the response by customizing the XmlResponseFormatter
components property contentType
to use custom value and then setting the custom formatter on runtime rather than using echo
manually as since 2.0.14
Yii does not allow echoing in the controller, hence should not be followed. Also using this method will set the charset
too for the content-type
headers automatically.
You should do the following to follow a conventional approach
public function actionResponder()
{
$filePath = $_SERVER['DOCUMENT_ROOT'] . '/assets/test.xml';
$xml = new XmlResponseFormatter();
$xml->contentType = 'multipart/form-data';
Yii::$app->response->format='xml';
Yii::$app->response->formatters['xml']=$xml;
$xmlFile = file_get_contents($filePath);
return $xmlFile;
}
You can send response with custom content type in this way:
Yii::$app->response->format = Response::FORMAT_RAW;
Yii::$app->response->headers->add('Content-Type', 'multipart/form-data');
Yii::$app->response->content = file_get_contents($filePath);
return Yii::$app->response;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.