【问题标题】:How to send image from Laravel controller to API Rest [closed]如何将图像从 Laravel 控制器发送到 API Rest [关闭]
【发布时间】:2020-05-26 21:01:50
【问题描述】:

我需要从 Laravel 中的存储中获取图像并将其从控制器发送到外部 API REST。

我正在使用 guzzlehttp multipart 但 API 没有收到文件,返回 file = null

【问题讨论】:

    标签: laravel api guzzle6 guzzle


    【解决方案1】:

    这就是我几天前的做法(从请求中获取文件):

    对于单个文件:

    public function storeProductImage(Request $request, $id){
        $image = $request->file('image');
        $body = [
                  "headers" => [
                  "Accept" => "multipart/form-data"
                 ],
                 "multipart" => [
                  "name" => "image",
                  "contents" => file_get_contents($image),
                  "filename" => $image->getClientOriginalName()
                ]
             ];
        return \GuzzleHttp\Client::request('POST', 'product/'.$id.'/images', $body);
    }
    


    对于多个文件:

    public function storeProductImage(Request $request, $id){
        $body = [ "headers" => [
                    "Accept" => "multipart/form-data"
                  ],
                  "multipart" => []
               ];
        $images = $request->file('image');
        if (is_array($images)) {
            foreach ($images as $image) {
                array_push($body["multipart"], ["name" => "image[]",
                    "contents" => file_get_contents($image),
                    "filename" => $image->getClientOriginalName()]);
            }
        }
        return \GuzzleHttp\Client::request('POST', 'product/'.$id.'/images', $body);
    }
    

    【讨论】:

    • 谢谢,我会尝试一下?
    • 非常感谢你救了我
    猜你喜欢
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 2019-04-06
    • 2021-04-09
    • 2016-05-06
    • 1970-01-01
    • 2019-11-13
    • 1970-01-01
    相关资源
    最近更新 更多