【问题标题】:Trying to use Laravel HTTP to upload a file to a 3rd party尝试使用 Laravel HTTP 将文件上传到第三方
【发布时间】:2023-01-17 18:44:48
【问题描述】:

我有以下 Postman 测试第三方 API 的请求;

我想做的是使用 Laravel 的 HTTP 类将其转换为代码,我目前拥有的代码是;

public function uploadToThridParty()
{
    $uploadContents = [
        'id' => 'this-is-my-id',
        'fileUpload' => true,
        'frontfile' => Storage::get('somefrontfile.jpg'),
        'sideview' => Storage::get('itsasideview.png'),
    ];

    $request = Http::withHeaders(
        [
            'Accept' => 'application/json',
        ]
    );

    $response = $request
        ->asForm()
        ->post(
            'https://urltoupload.com/upload', $uploadContents
        )
}

但是每次我运行它时,第 3 方 API 都会返回 Invalid ID,即使我使用具有相同 ID 的 Postman 也能正常工作。

我似乎无法弄清楚我的代码哪里出了问题;

【问题讨论】:

  • Storage::get 将文件内容作为字符串返回,我怀疑请求类是否知道它应该基于此执行实际的文件上传(而不是仅仅发送字符串值)。 laravel.com/docs/9.x/http-client#multi-part-requests
  • @CBroe ...我可以发送多个文件并仍然保留邮递员想要的结构吗? ...对不起,我对此有点陌生
  • 我认为您应该能够多次调用 attach 方法。 $response = Http::attach(...)::attach(...)->post(...);

标签: php laravel


【解决方案1】:

正如@Cbroe 在发送发布请求之前提到的附加文件一样,你可以像这个例子一样做:

public function uploadToThridParty()
{
    $uploadContents = [
        'id' => 'this-is-my-id',
        'fileUpload' => true
    ];

    $request = Http::withHeaders(
        [
            'Accept' => 'application/json',
        ]
    );

    $response = $request
        ->attach(
        'frontfile', file_get_contents(storage_path('somefrontfile.jpg')), 'somefrontfile.jpg' 
         )
        ->attach(
        'sideview', file_get_contents(storage_path('itsasideview.png')), 'itsasideview.jpg' 
         )
        ->post(
            'https://urltoupload.com/upload', $uploadContents
        )
}

另外我认为您需要删除 asForm 方法,因为它会将您的标头接受类型覆盖为 application/x-www-form-urlencoded 这就是您的异常是 Invalid ID 的方式

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-05
    • 2015-09-20
    • 1970-01-01
    • 2017-12-09
    • 2015-10-18
    • 2016-10-27
    相关资源
    最近更新 更多