Magento 2自定义REST API多部分/表单数据



我正在使用Magento2自定义REST API。我需要上传一个.csv文件vai API。我一直在寻找在我的REST API中支持multipart/form-data的解决方案。但不幸的是,我们还没有找到合适的解决方案。请帮助我分享关于如何在Magento2 REST API中支持multipart/form-data的任何想法?

我希望我能帮助你。

您可以通过以下操作将响应类型添加到magento REST API:

  • 创建webapi响应渲染器
    {ROOT}appcode{VENDOR_NAME}WebapiWebapiRestResponseRenderer
<?php

namespace {VENDOR_NAME}WebapiWebapiRestResponseRenderer;
use MagentoFrameworkWebapiRestResponseRendererInterface;
use MagentoFrameworkWebapiException 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}appcode{VENDOR_NAME}Webapietcdi.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="MagentoFrameworkWebapiRestResponseRendererFactory">
<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}WebapiWebapiRestResponseRendererMultipart</item>
</item>
</argument>
</arguments>
</type>
</config>

根据您的项目更改{VENDOR_NAME}和{ROOT}即可
如果您需要任何澄清,请随时询问
编辑:
webapi.xml非常基础。要获得我们在response中创建的响应类型,您必须将AcceptHTMLHeader(在ajax调用中(设置为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}WebapiApi{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="MagentoFrameworkWebapiRestResponseRendererFactory">
<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}WebapiWebapiRestResponseRendererMultipart</item>
</item>
</argument>
</arguments>
</type>
<preference for="{VENDOR_NAME}WebapiApi{API_CLASS_NAME}Interface"
type="{VENDOR_NAME}WebapiModelApi{API_CLASS_NAME}" />
</config>

请参阅有关创建自定义API路由/控制器的本教程。

最新更新