代码之家  ›  专栏  ›  技术社区  ›  trogwar

Guzzle中的Mimic curl工作脚本(多部分数据和二进制上传一起)

  •  1
  • trogwar  · 技术社区  · 1 年前

    我有一个非常有效的curl命令(通过Stability API使用img2img):

    curl --request POST 'https://api.stability.ai/v1/generation/stable-diffusion-xl-1024-v1-0/image-to-image' \
        --header 'Content-Type: multipart/form-data' \
        --header 'Accept: application/json' \
        --header 'Authorization: Bearer somesecrettoken' \
        --form 'init_image=@"/full/path/to/init_image.png"' \
        --form 'text_prompts[0][text]=Beautiful php code' \
        --output '/full/path/to/response.json'
    

    我已经用Guzzle v.6.5.8尝试过这个PHP代码,它给了我HTTP 520:

    (new Client())
    ->post(
        'https://api.stability.ai/v1/generation/stable-diffusion-xl-1024-v1-0/image-to-image',
        [
            RequestOptions::HEADERS   => [
                'Accept'        => 'application/json',
                'Authorization' => 'Bearer somesecrettoken',
                'Content-Type'  => 'multipart/form-data',
            ],
            RequestOptions::MULTIPART => [
                [
                    'name'     => 'text_prompts[0][text]',
                    'contents' => 'Beautiful php code',
                ],
                [
                    'name'     => 'init_image',
                    'contents' => (new File('/full/path/to/init_image.png'))->getContent(),
    //                'contents' => \GuzzleHttp\Psr7\Utils::tryFopen('/full/path/to/init_image.png', 'rb'), // This won't work too
                ],
            ],
            RequestOptions::SINK      => '/full/path/to/response.json',
            RequestOptions::DEBUG     => true,
        ],
    )
    

    我在这里做错了什么?

    1 回复  |  直到 1 年前
        1
  •  1
  •   C3roe    1 年前

    假设 app.stability.key 仅包含您的 somesecrettoken 你的 Authorization 标头将缺少 Bearer 关键字。

    此外,将 Content-Type 页眉可能是个好主意。此标头最终需要包括库用于分离此请求的各个部分的边界值,并且在使用时 RequestOptions::MULTIPART ,它应该自己添加这个标头,包括边界值。如果显式指定它,可能会覆盖库将自己创建的内容,然后边界就会丢失。