MelancholicTurnip
MelancholicTurnip

Reputation: 33

Google Drive Api PHP multipart upload empty content

my issue is the following. When using the google drive api V3 and php to upload a file to google drive, the file uploaded is empty, with a filesize of 0 bytes. All the metadata uploads no problem.

session_start();
$file_tmp=$_SESSION['file_tmp'];
$drive = new Google_Service_Drive($client);

$data = file_get_contents($file_tmp);
    $file = new Google_Service_Drive_DriveFile(array(
      'data' => $data,
      'mimeType' => $file_type,
      'name' => $file_name,
      'description'=>$lolol,
      'uploadType' => 'multipart',
      'parents' => array($folderID),
      'uploadType' => 'multipart'
  ));
      $createdFile = $drive->files->create($file);

For anyone wondering, if I echo $file_tmp I get a path such as /private/var/tmp/phpDpmi83 .(I got this from a html form with input type file)

Originally i didn't have an UploadType and other forums said that was the issue, but I added that and still nothing. Any suggestions?

Upvotes: 1

Views: 613

Answers (1)

Tanaike
Tanaike

Reputation: 201643

I believe your goal as follows.

  • You want to upload a file with multipart/form-data to the specific folder in Google Drive using Drive API.
  • You want to achieve this using googleapis for PHP.
  • In your script, $drive can be used for uploading the file.

For this, how about this answer?

Modification point:

  • In your script, please separate the metadata and file content. By this, I think that your script works.

When above point is reflected to your script, it becomes as follows.

Modified script:

session_start();
$file_tmp=$_SESSION['file_tmp'];
$drive = new Google_Service_Drive($client);

$data = file_get_contents($file_tmp);

// I modified below script.
$file = new Google_Service_Drive_DriveFile(array(
    'mimeType' => $file_type,
    'name' => $file_name,
    'description'=>$lolol,
    'parents' => array($folderID),
));
$file_content = array(
    'data' => $data,
    'uploadType' => 'multipart'
);
$createdFile = $drive->files->create($file, $file_content);

Note:

  • In this modification, it supposes that $data is the file content. If your $file_tmp cannot be used, please test using a sample file.
  • In this case, the maximum file size is 5 MB. Please be careful this.

References:

Upvotes: 2

Related Questions