希望能帮到你。
您可以通过执行以下操作将响应类型添加到 magento REST API:
- 创建 webapi 响应渲染器
{ROOT}\app\code\{VENDOR_NAME}\Webapi\Webapi\Rest\Response\Renderer
<?php
namespace {VENDOR_NAME}\Webapi\Webapi\Rest\Response\Renderer;
use Magento\Framework\Webapi\Rest\Response\RendererInterface;
use Magento\Framework\Webapi\Exception as WebApiException;
class Multipart implements RendererInterface
{
/**
* Renderer mime type.
*/
const MIME_TYPE = 'multipart/form-data';
/**
* @return string
*/
public function getMimeType() {
return self::MIME_TYPE;
}
/**
* @param object|array|int|string|bool|float|null $data
* @return string
* @throws WebApiException
*/
public function render($data) {
// return reponse according to your needs
if (is_string($data)) {
return $data;
}
throw new WebApiException(
__('Internal Server Error')
);
}
}
- 将该渲染器添加到支持的 webapi 响应中
{ROOT}\app\code\{VENDOR_NAME}\Webapi\etc\di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Framework\Webapi\Rest\Response\RendererFactory">
<arguments>
<argument name="renders" xsi:type="array">
<item name="multipart" xsi:type="array">
<item name="type" xsi:type="string">multipart/form-data</item>
<item name="model" xsi:type="string">{VENDOR_NAME}\Webapi\Webapi\Rest\Response\Renderer\Multipart</item>
</item>
</argument>
</arguments>
</type>
</config>
根据您的项目更改 {VENDOR_NAME} 和 {ROOT} 即可。
如果您需要任何说明,请随时询问。
编辑:
webapi.xml 非常基础。要在响应中获取我们在上面创建的响应类型,您必须将 Accept HTML Header(在 ajax 调用 f.e. 中)设置为 multipart/form-data。 Magento 2 API 响应始终通过检查此标头来呈现。
{ROOT}/app/code/{VENDOR_NAME}/Webapi/etc/webapi.xml
<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../app/code/Magento/Webapi/etc/webapi.xsd">
<route url="/V1/yourMethod" method="GET">
<service class="{VENDOR_NAME}\Webapi\Api\{API_CLASS_NAME}Interface" method="yourMethod" />
<resources>
<resource ref="anonymous" />
</resources>
</route>
</routes>
现在您只需在di.xml 中为接口设置一个首选模型。
{ROOT}/app/code/{VENDOR_NAME}/Webapi/etc/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
<type name="Magento\Framework\Webapi\Rest\Response\RendererFactory">
<arguments>
<argument name="renders" xsi:type="array">
<item name="multipart" xsi:type="array">
<item name="type" xsi:type="string">multipart/form-data</item>
<item name="model" xsi:type="string">{VENDOR_NAME}\Webapi\Webapi\Rest\Response\Renderer\Multipart</item>
</item>
</argument>
</arguments>
</type>
<preference for="{VENDOR_NAME}\Webapi\Api\{API_CLASS_NAME}Interface"
type="{VENDOR_NAME}\Webapi\Model\Api\{API_CLASS_NAME}" />
</config>
See this tutorial 关于创建自定义 API 路由/控制器。