I currently have a function that successfully uploads jpg files to google drive. I was wondering how to modify the function so that I can upload pdf, jpg, png, and docx files to google drive as well. Here is my code:
function uploadFiles($filePath) { $file = new Google_Service_Drive_DriveFile(); $file->setName(uniqid().'.jpg'); $file->setDescription('A test document'); $file->setMimeType('image/jpeg'); $data = file_get_contents($filePath); $createdFile = $this->service->files->create($file, array( 'data' => $data, 'mimeType' => 'image/jpeg', 'uploadType' => 'multipart' )); }
Any help is appreciated. Thanks.
Advertisement
Answer
In the case that the files of pdf, jpg, png, and docx
are uploaded as pdf, jpg, png, and docx
, when a file is uploaded with the method of Files: create in Drive API, it seems that the mimeType of the file is automatically detected. I thought that in your case, this situation can be used. So please modify your script as follows.
Modified script:
function uploadFiles($filePath) { $file = new Google_Service_Drive_DriveFile(); $file->setName(uniqid()); $file->setDescription('A test document'); $data = file_get_contents($filePath); $createdFile = $this->service->files->create($file, array( 'data' => $data, 'uploadType' => 'multipart' )); }
- By above modification, for
pdf, jpg, png, and docx
, the uploaded file has the correct mimeType.