【问题标题】:How to post an image to this web service如何将图像发布到此 Web 服务
【发布时间】:2020-07-29 16:01:03
【问题描述】:

http://labelary.com/viewer.html

此网络服务有一个“未记录”服务,您可以在其中发布 png,然后将编码为 zpl 文件的图像发回给您(用于标签打印机)。 don't worry, I'm not trying to do anything they don't want me to do, it's mentioned at the bottom here that they allow this undocumented use of their api

因此,当您在门户网站中使用该 api 时,它会向此 url 发出 post 请求:http://api.labelary.com/v1/graphics

如果我上传一个 png,然后查看 Chrome 开发者工具的网络选项卡,我可以看到它发布了一个表单数据,file: (binary)

在他们的文档中,他们实际上推荐了这个 Ruby 库:https://github.com/rjocoleman/labelary——这已经实现了一种将带有文件的发布请求发送到该 url 并取回 zpl 数据的方法。

如果您导航到labelary/lib/labelary/image.rb,您可以看到encode 函数的代码:

    def encode
      response = Labelary::Client.connection.post '/v1/graphics', { file: @file }, { Accept: 'application/json' }
      image = response.body

      return '^GFA,' + image['totalBytes'].to_s + ',' + image['totalBytes'].to_s + ',' + image['rowBytes'].to_s + ',' + image['data'] + '^FS'
    end

它使用faraday 请求库发出该请求,如果这有任何相关性的话。

所以基本上,我正在尝试使用 Guzzle 在 php+laravel 中实现这个请求。 现在我知道如何发出 post 请求,但我不完全知道如何发送图像,然后我四处搜索并想出了这段代码,但它不起作用:

        $pngPath = storage_path('image.png'); // this is a confirmed real file on my system in the storage folder
        $client = new \GuzzleHttp\Client();
        $response = $client->request('POST', 'http://api.labelary.com/v1/graphics', [
            'headers' => [
                'Content-Type' => 'multipart/form-data'
            ],
            'multipart' => [
                [
                    'name'     => 'file',
                    'contents' => fopen($pngPath, 'r'),
                ]
            ]
        ]);

当我提出这个请求时,我收到了这个没有太多细节的错误消息:ERROR: HTTP 400 Bad Request

【问题讨论】:

    标签: php laravel file guzzle


    【解决方案1】:

    我只需要修改一点我的请求,它就奏效了——我认为可能是 Content-Type 标头把我搞砸了。

    这是请求现在的样子:

                $client = new \GuzzleHttp\Client();
                $response = $client->request('POST', 'http://api.labelary.com/v1/graphics', [
                    'headers' => [
                        // 'Content-Type' => 'multipart/form-data'
                        'Accept' => 'application/json'
                    ],
                    'multipart' => [
                        [
                            'Content-Type' => 'image/png',
                            'name'     => 'file',
                            'contents' => fopen($pngPath, 'r'),
                            'filename' => basename($pngPath)
                        ]
                    ]
                ]);
    

    抱歉浪费了大家的时间!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-03
      • 1970-01-01
      • 1970-01-01
      • 2017-10-13
      • 1970-01-01
      • 1970-01-01
      • 2021-08-21
      • 2015-07-28
      相关资源
      最近更新 更多