Create folder and insert file in Google Drive
- by web_student
I am trying to create a new folder in Drive and upload one (or more) files to that created folder. I use the code below, but the result is that both the folder and the file are placed in the root of my Drive.
$client->setAccessToken($_SESSION['accessToken']);
//create folder
$folder_mime = "application/vnd.google-apps.folder";
$folder_name = 'New Folder';
$service = new Google_DriveService($client);
$folder = new Google_DriveFile();
$folder->setTitle($folder_name);
$folder->setMimeType($folder_mime);
$service->files->insert($folder);
//upload file
$file_name = $_FILES["uploadFile"]["name"];
$file_mime = $_FILES["uploadFile"]["type"];
$file_path = $_FILES["uploadFile"]["tmp_name"];
$service = new Google_DriveService($client);
$file = new Google_DriveFile();
$file->setParents(array($folder_name));
$file->setTitle($file_name);
$file->setDescription('This is a '.$file_mime.' document');
$file->setMimeType($file_mime);
$service->files->insert(
$file,
array(
'data' => file_get_contents($file_path)
)
);