Dhamo's avatar
Level 1

Cannot upload file to google drive using guzzle

I'm trying to upload files to drive (v3 api) by using guzzle, but it returns unsupported content error. the same request works fine in postman

0 likes
7 replies
vincent15000's avatar

Perhaps you could post your code here, without seeing your code, it will be difficult to help you.

Dhamo's avatar
Level 1
$data = [
            "name" => $originalFileName,
            "parents" => [
                "<id>"
            ],
        ];
		$client = new Client();
		$headers = [
            'Authorization' => 'Bearer '.$token,
        ];
        $grantAccess = $client->request('POST', 'url', [
                    'multipart' => [
                        [
                            'name'     => 'metadata',
                            'contents' => json_encode($data)
                        ],
                        [
                            'name'     => 'media',
                            'contents' => file_get_contents($file)
                        ]
                    ],
                    'headers' => $headers,
                ]);
Tray2's avatar

@Dhamo Where does the $file come from?

Are you using a form for uploading?

$res = $client->request('POST', $this->base_api . $endpoint, [
    'auth'      => [ env('API_USERNAME'), env('API_PASSWORD') ],
    'multipart' => [
        [
            'name'     => 'FileContents',
            'contents' => file_get_contents($path . $name),
            'filename' => $name
        ],
        [
            'name'     => 'FileInfo',
            'contents' => json_encode($fileinfo)
        ]
    ],
]);

Stolen from this post https://stackoverflow.com/questions/38133244/upload-file-using-guzzle-6-to-api-endpoint

Dhamo's avatar
Level 1

@Tray2 the code you shared is similar to what i have done. but the response is 400 with bad content message

Dhamo's avatar
Dhamo
OP
Best Answer
Level 1

I used filesystem to resolve this issue

$client = new Client();
$headers = [
    'Authorization' => 'Bearer '.$token,
];
$storeToDrive = $client->post('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart', [
    'multipart' => [
        [
            'name'     => '',
            'contents' => fopen('your meta file path', 'r'),
        ],
        [
            'name'     => '',
            'contents' => fopen('path of the file that you want to upload', 'r'),
        ]
    ],
    'headers' => $headers,
]);

Please or to participate in this conversation.