Search code examples
phplaravelimageuploadimgur

How to upload images to Imgur using Laravel?


Is there any way I can upload images to Imgur using Laravel.

I am currently using

$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())));

My blade file is

<tr>
    <td>Thumbnail</td>
    <td>
        <input type="file" name="file" id="file">
    </td>
</tr>

I keep on getting Call to a member function path() on null

What I want to do is to get a file upload, upload it to Imgur and get the URL back to insert it into my database.


Solution

  • Try this,

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