Shin Shin - 6 months ago 219
PHP Question

Upload files to Google Drive using php curl

I'm implementing a file uploading using php curl for some reasons.
But I can't upload a file and get

false
response.
I refered Google Drive Document.
Any idea?

$token = "xxxx";
$url = "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart";

$inputarray = '';
$inputarray .= "--foo_bar_baz\r\n";
$inputarray .= "Content-Type: application/json; charset=UTF-8\r\n\r\n";
$inputarray .= "{\r\n";
$inputarray .= "\"name\": \"upload.jpg\"\r\n";
$inputarray .= "}\r\n\r\n";
$inputarray .= "--foo_bar_baz\r\n";
$inputarray .= "Content-Type:image/jpeg\r\n\r\n";
$inputarray .= file_get_contents("upload.jpg") . "\r\n";
$inputarray .= "--foo_bar_baz--\r\n";


$headers = array(
'Content-Type: multipart/related; boundary=foo_bar_baz',
'Authorization: Bearer ' . $token,
'Content-Length: ' . strlen($inputarray)
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $inputarray);

$output = curl_exec($ch);
curl_close($ch);

echo $output;

Answer

I could upload files by changing CURLOPT_POSTFIELDS parameters to array data.

$token = "xxx";
$url = "https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart";

$headers = array(
    "Content-Type:multipart/related",
        "Authorization: Bearer ".$token
    );

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);

$data1 = '@'.realpath('./metadata.json').';type=application/json;charset=UTF-8';
$data2 = '@'.realpath('./test.csv').';type=text/csv';

$postdata = array(
  'metadata'=>$data1,
  'file'=>$data2
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);

$output = curl_exec($ch);
curl_close($ch);

echo $output;