求助:将可用的Stability API curl脚本转为Guzzle PHP代码时遇HTTP 520错误
问题分析与修正方案
你的代码存在两个关键错误,导致请求无法被Stability API正确解析,返回520错误:
1. 手动设置了错误的Content-Type头
当使用Guzzle的MULTIPART选项时,框架会自动生成包含boundary分隔符的multipart/form-data头(比如multipart/form-data; boundary=------------------------xxx)。手动指定Content-Type: multipart/form-data会覆盖这个自动生成的头,缺少boundary的情况下,服务器无法正确分割multipart表单数据,导致处理失败。
2. 图片上传的格式错误
你当前的图片内容传递方式没有正确标识这是文件上传:
- 使用
File::getContent()会把图片内容转为字符串,但服务器无法识别这是文件字段; - 使用
tryFopen获取流时,缺少filename参数,服务器无法判断字段类型。
修正后的代码
(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,让Guzzle自动处理 ], RequestOptions::MULTIPART => [ [ 'name' => 'text_prompts[0][text]', 'contents' => 'Beautiful php code', ], [ 'name' => 'init_image', 'contents' => fopen('/full/path/to/init_image.png', 'rb'), // 以二进制只读模式打开文件流 'filename' => 'init_image.png', // 指定文件名,帮助服务器识别文件类型 ], ], RequestOptions::SINK => '/full/path/to/response.json', RequestOptions::DEBUG => true, ], );
内容的提问来源于stack exchange,提问作者trogwar
相关产品推荐
相关产品推荐

