Search code examples
google-drive-apiguzzlephp-curl

How can I upload files to GoogleDrive in “multipart” type by using Guzzle?


With the help of @Tanaike(see here), I can successfully upload files to GoogleDrive by using php-curl, here is my code by using php-curl:

function uploadByCurl($uploadFilePath, $accessToken){
    $ch = curl_init();
    $boundary = md5(mt_rand() . microtime());
    //MetaData
    $params = json_encode([
        'name' => basename($uploadFilePath),
        'description' => 'This is a test',
    ]);
    $fileContent = file_get_contents($uploadFilePath);

    $dataToUpload = "--{$boundary}\r\n";
    $dataToUpload .= "Content-Type: application/json\r\n\r\n";
    $dataToUpload .= "{$params}\r\n";
    $dataToUpload .= "--{$boundary}\r\n";
    $dataToUpload .= "Content-Transfer-Encoding: base64\r\n\r\n";
    $dataToUpload .= base64_encode($fileContent) . "\r\n";
    $dataToUpload .= "--{$boundary}--";

    $options = [
        CURLOPT_URL =>  'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart',
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POSTFIELDS => $dataToUpload,
        CURLOPT_HTTPHEADER => [
            'Authorization:Bearer ' . $accessToken,
            'Content-Type: multipart/related; boundary=' . $boundary,
        ],
        //In case you're in Windows, sometimes will throw error if not set SSL verification to false
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => 0,
    ];
    //In case you need a proxy
    //$options[CURLOPT_PROXY] = 'http://127.0.0.1:1087';

    curl_setopt_array($ch, $options);
    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    }
    curl_close ($ch);
    return $result;
}

$uploadFilePath = '<YOU-FILE-ABS-PATH>';
$accessToken = '<YOU-ACCESS-TOKEN>';
$ret = uploadByCurl($uploadFilePath, $accessToken);
var_dump($ret);

Response json:

{
 "kind": "drive#file",
 "id": "1lkuCTeMooRmde8uzNa7COUTTCLAk_jdq",
 "name": "timg (12).jpeg",
 "mimeType": "image/jpeg"
}

But when I'm trying to use Guzzle6(An curl client written by PHP) to do the same thing, the file(image file) can successfully upload but its name is "Untitled" and I can't preview the image(see the screenshot below):

enter image description here

enter image description here

Here is my code snippet by using Guzzle:

function uploadByGuzzle($uploadFilePath, $accessToken){
    $boundary = md5(mt_rand() . microtime());
    //MetaData
    $params = json_encode([
        'name' => basename($uploadFilePath),
        'description' => 'This is a test',
    ]);
    $fileContent = file_get_contents($uploadFilePath);

    $dataToUpload = "--{$boundary}\r\n";
    $dataToUpload .= "Content-Type: application/json\r\n\r\n";
    $dataToUpload .= "{$params}\r\n";
    $dataToUpload .= "--{$boundary}\r\n";
    $dataToUpload .= "Content-Transfer-Encoding: base64\r\n\r\n";
    $dataToUpload .= base64_encode($fileContent) . "\r\n";
    $dataToUpload .= "--{$boundary}--";

    $GuzzleConfig = [
        'base_uri' => 'https://www.googleapis.com/upload/drive/v3/files/',
        'timeout'  => 30.0,
    ];
    //In case you need a proxy
    $GuzzleConfig['proxy'] = 'http://127.0.0.1:1087';
    //GuzzleHttp
    $client = new Client($GuzzleConfig);
    $uri = '?uploadType=multipart';
    $response = $client->request('POST', $uri, [
        'verify' => false,
        'headers' => [
            'Authorization' => 'Bearer ' . $accessToken,
            'Content-Type' => 'Content-Type: multipart/related; boundary=' . $boundary,
        ],
        'body' => $dataToUpload,
    ]);

    $string = $response->getBody()->getContents();
    return $string;
}

$uploadFilePath = '<YOU-FILE-ABS-PATH>';
$accessToken = '<YOU-ACCESS-TOKEN>';
$ret = uploadByGuzzle($uploadFilePath, $accessToken);
var_dump($ret);

Solution

  • I think that the request body is correct. In your script, Content-Type is not correct. In this case, I think that body is sent as application/octet-stream. By this, the file of Untitled is created. And I think that it is the text data of the request body.

    So how about this modification?

    From:

    'Content-Type' => 'Content-Type: multipart/related; boundary=' . $boundary,
    

    To:

    'Content-Type' => 'multipart/related; boundary=' . $boundary,