I'm trying to upload a file to a specific folder in Google Drive API, but I'm having trouble getting it to work. I've tried both through code in Apex and using Postman to make HTTP requests, but the file always ends up in the root folder.
Here's the Apex code I'm using to make the HTTP request:
public void uploadFileToDrive(String folderId) {
// Get the HTTP request body
String requestBody = createRequestBody();
String strEndpoint = 'https://www.googleapis.com/upload/drive/v3/files?
uploadType=multipart&parents=' + folderId;
// Make the HTTP POST request to upload the file to the specified folder
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint(strEndpoint);
request.setHeader('Authorization', 'Bearer ' + access_token);
request.setHeader('Content-Type', 'multipart/related; boundary="----boundary"');
request.setBody(requestBody);
request.setMethod('POST');
HttpResponse response = http.send(request);
if (response.getStatusCode() == 200) {
// File uploaded successfully
System.debug('File uploaded successfully to Google Drive');
} else {
// Error uploading file
System.debug('Error uploading file to Google Drive: ' + response.getStatus() + ' - ' + response.getBody());
}
}
I've tried passing the folder ID to the parents parameter in the URL like this:
https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&parents=%5C\<folder ID>
But it's not working. The file keeps getting uploaded to the root folder.
I've also tried testing the endpoint in Postman, but I'm getting the same result. Here's what I'm sending in the form-data:
Key: file, Value: test.png
Key: parents, Value: \<folder ID\>
I'm setting the Content-Type header to multipart/form-data.
Can anyone help me figure out what I'm doing wrong? Thank you in advance!
I'm trying to upload a file to a specific folder in Google Drive API, but I'm having trouble getting it to work. I've tried both through code in Apex and using Postman to make HTTP requests, but the file always ends up in the root folder.
I tried passing the folder ID to the parents parameter in the URL like this:
https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&parents=%5C\<folder ID>
I expected the file to be uploaded to the specified folder, but it keeps getting uploaded to the root folder. I also tried testing the endpoint in Postman, but I'm getting the same result.
Can anyone help me figure out what I'm doing wrong? Thank you in advance!
The folder id must be added to the form data, not to the URL. But the key is not parents
, but metadata
.
Key:metadata, value:{"parents":["folderid"]}
Look here for metadata options and correct JSON representation: Google Drive API Files Overview.