【问题标题】:Laravel Http Client cannot attach files contents requiredLaravel Http 客户端无法附加所需的文件内容
【发布时间】:2021-02-13 03:38:49
【问题描述】:

我一直在寻找答案,但没有找到。

问题很简单,我正在尝试使用此处记录的 Illuminate\Support\Facades\Http 类发出 HTTP 请求https://laravel.com/docs/8.x/http-client#multi-part-requests

我的代码:-

$picture = fopen(public_path('/temp_pass/image.jpeg'),'r');

$response = Http::attach('attachment', $picture)
             ->withHeaders(['Accept'=>'application/json'])
             ->post('mydomain.com/item/store',['item_id' => 'my_item_id']);

图片网址没问题。要发送到的域也可以。不幸的是,我收到了这个错误

A 'contents' key is required  

我希望这里的优秀开发人员可以帮助我解决这个问题。

【问题讨论】:

    标签: laravel http post httpclient multipartform-data


    【解决方案1】:

    Http::attach('attachment', $picture) 行引用了以下文件和方法。

    Illuminate\Http\Client\PendingRequest.php

    public function attach($name, $contents = '', $filename = null, array $headers = [])
    

    根据我的测试,$contents 为 falsy(空、null、false、0 等)时发生A 'contents' key is required

    在您的情况下,这是指$picture。您应该检查$picture 实际上是否包含预期的文件流。在 HTTP 请求之前转储它以进行测试。

    dd($picture);
    
    // stream resource @7 ▼
    //   timed_out: false
    //   blocked: true
    //   eof: false
    //   wrapper_type: "plainfile"
    //   stream_type: "STDIO"
    //   mode: "r"
    //   unread_bytes: 0
    //   seekable: true
    //   uri: "/.../image.jpeg"
    //   options: []
    // } 
    

    【讨论】:

    • 我在 dd 流资源 @15 ▼ timed_out: false 阻塞: true eof: false wrapper_type: "plainfile" stream_type: "STDIO" mode: "r" unread_bytes: 0 seekable: true uri: “/private/var/tmp/phppWwrLT”选项:[] }
    • fopen() 和您遗漏的 HTTP 请求之间是否有任何附加代码?
    • 没有额外的代码。我什至尝试使用 file_get_contents(),并确保有一个文件,因为我确实尝试使用浏览器打开它。
    • 你确定你引用了正确的外观use Illuminate\Support\Facades\Http;,而不是来自另一个包的类似名称的类吗?
    • 是的,我确定。我确实使用过 Illuminate\Support\Facades\Http。当我不使用附加方法时它可以工作。
    猜你喜欢
    • 2020-09-11
    • 2021-07-03
    • 2021-12-24
    • 1970-01-01
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多