通过CSV格式上传Restler 3rc5格式的CSV文件


Upload a CSV in Restler 3rc5 through CSVformat

我正试图将CSV发布到我们的API之一,并从中导入数据。我看了看CSVFormat,它看起来像是在处理CSV的解析,并把结果放在一个数组中,这太棒了!然而,我有一些问题时,试图做POST调用。

在我的index.php文件中,我将支持的格式设置如下:

$r->setSupportedFormats('JsonFormat', 'CsvFormat');

然而,当我使用Postman向API发送CSV文件时,我得到以下错误:

{
    "error": {
        "code": 403,
        "message": "Content type `multipart/form-data` is not supported."
    },
    "debug": {
        "source": "Restler.php:468 at setup stage",
        "stages": {
            "success": [],
            "failure": [
                "get",
                "route",
                "negotiate",
                "message"
            ]
        }
    }
}

我尝试将CSV格式更改为UploadFormat,它可以工作,但CSV没有被解析。我如何使用POST上传CSV到我的API,并通过CsvFormat解析它?

您需要将UploadFormat添加到支持的格式

你的api类可以像
<?php
use Luracast'Restler'Scope;
class Api
{
    public function post(array $csv)
    {
        $parsed_data = Scope::get('CsvFormat')->decode(file_get_contents($csv['tmp_name']));
        return $parsed_data;
    }
}

您可以使用如下的表单来发布您的csv文件

<html>
<body>
    <form action="/api" method="post" enctype="multipart/form-data">
        <label for="file">Filename:</label><input type="file" name="csv" id="file" /> <br />
        <input type="submit" name="submit" value="Submit" />
    </form>
</body>
</html>