Google Drive SDK (PHP Client Library) - Upload file but unreadable on the Google Drive UI

Question!

Here is my code to upload a file:

private function addFile(File $file, $folderProject, User $user) {

    $fileToUpload = new Google_DriveFile();
    $fileToUpload->setTitle($file->getName());

    //set mime type
    $fileToUpload->setMimeType($file->getMimeType());

    //build parent and set id
    $parent = new Google_ParentReference();
    $parent->setId($folderProject->getId());

    //set parent to file
    $fileToUpload->setParents(array($parent));

    $data = file_get_contents($file->getPath());

    $createdFile = $this->service->files->insert($fileToUpload, array(
            'data' => $data,
            'mimeType' => $file->getMimeType(),
    ));

}

When I upload for example a docx using this PHP code the file append to be unreadable on the Google Drive website (it shows up the XML structure of the docx) and it is showing up like this in my Google Drive folder:

unreadable

And when i try to upload a docx directly through Google Drive UI it showing up like this (what i want): readable

I'm pretty sure that the problem is coming from the fact the Google Drive UI tries to open the file in a different way because i uploaded it through my app, but i don't want that :)

(i have the same problem with other kind of files)


I tried to set the parameter 'convert' = true in the array but then i got this error during the upload:

..convert=true&uploadType=multipart&key=AI39si49a86oqv9fhb9yzXp7FCWL-cSqwFiClHZ??qS3Y3r9Hw8ujtSNlZEWZyFKBp_id7LUyFaZTJ97pMeb0XqHznycK7JJ9o_Q: (500) Internal Error

Documentation: https://developers.google.com/drive/v2/reference/files/insert

=> But anyway i don't think to convert is the right solution, i just want to be able to see the content as if i uploaded the file through the Google Drive UI


If i open the docx from my Google Drive Sync folders and I edit and save it, I will be able to see it through the Google Drive UI (showing with the W logo)



Answers
I also getting the same problem.

But the difference is that , I am uploading pdf and able to view pdf in google drive UI.

I need to automatically convert it to google doc format by api code after adding new pdf.

If I change $mimeType = 'application/vnd.google-apps.document'; then got below error
https://www.googleapis.com/upload/drive/v2/files?convert=true&uploadType=multipart: (400) Bad Request

if I add optional parameter

$createdFile = $service->files->insert($file, array(
  'data' => $data,
  'mimeType' => $mimeType,
'convert' => TRUE
));

Then no change , only pdf upload no conversion takes place.

do u have any suggestion , where I need to exactly add for convert parameter ?



This video can help you solving your question :)
By: admin