为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 Laravel 将图像上传到 Imgur?

如何使用 Laravel 将图像上传到 Imgur?

PHP
慕尼黑8549860 2023-08-19 17:33:16
有什么方法可以使用 Laravel 将图像上传到 Imgur。我目前正在使用$client = new \GuzzleHttp\Client();$response = $client->request('POST', 'https://api.imgur.com/3/image', [    'headers' => [        'authorization' => 'Client-ID ' . 'app_id',        'content-type' => 'application/x-www-form-urlencoded',    ],    'form_params' => [        'image' => base64_encode(file_get_contents($request->file('thumbnail')))    ],]);return response()->json(json_decode(($response->getBody()->getContents())));我的刀片文件是<tr>    <td>Thumbnail</td>    <td>        <input type="file" name="file" id="file">    </td></tr>我继续得到Call to a member function path() on null我想要做的是上传文件,将其上传到 Imgur 并获取 URL 以将其插入到我的数据库中。
查看完整描述

2 回答

?
开满天机

TA贡献1786条经验 获得超12个赞

尝试这个,


$file = $request->file('file');

        $file_path = $file->getPathName();

        $client = new \GuzzleHttp\Client();

        $response = $client->request('POST', 'https://api.imgur.com/3/image', [

            'headers' => [

                    'authorization' => 'Client-ID ' . 'your-client-id-here',

                    'content-type' => 'application/x-www-form-urlencoded',

                ],

            'form_params' => [

                    'image' => base64_encode(file_get_contents($request->file('file')->path($file_path)))

                ],

            ]);

        $data['file'] = data_get(response()->json(json_decode(($response->getBody()->getContents())))->getData(), 'data.link');


查看完整回答
反对 回复 2023-08-19
?
慕桂英3389331

TA贡献2036条经验 获得超8个赞

Laravel 9 及以上答案的更新,


        use Illuminate\Support\Facades\Http;


        $file = $request->file('file');

        $file_path = $file->getPathName();

        $response = Http::withHeaders([

            'authorization' => 'Client-ID ' . 'your-client-id-here',

            'content-type' => 'application/x-www-form-urlencoded',

        ])->send('POST', 'https://api.imgur.com/3/image', [

            'form_params' => [

                    'image' => base64_encode(file_get_contents($request->file('file')->path($file_path)))

                ],

            ]);

        $data['file'] = data_get(response()->json(json_decode(($response->getBody()->getContents())))->getData(), 'data.link');


不要使用 http Facadepost()方法将表单发送到 imgur,它会序列化表单数据,服务器将收到 400 bad method 响应。


查看完整回答
反对 回复 2023-08-19
  • 2 回答
  • 0 关注
  • 77 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信