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

你离开我真会死。 提交于 2020-04-17 07:18:07

问题


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):

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

回答1:


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,


来源:https://stackoverflow.com/questions/60837047/how-can-i-upload-files-to-googledrive-in-multipart-type-by-using-guzzle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!