php 如何使用Laravel上传图片到Imgur?

lrpiutwd  于 2023-06-04  发布在  PHP
关注(0)|答案(2)|浏览(187)

有没有什么方法可以使用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回来插入到我的数据库。

hrirmatl

hrirmatl1#

试试这个

$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');
sdnqo3pr

sdnqo3pr2#

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 facade post()方法发送表单到imgur,它会序列化表单数据,服务器会得到400坏方法响应。

相关问题