Darshana
Darshana

Reputation: 71

How to solve the file upload issue by using google drive API?

I am trying to upload a file by using google drive API. I am doing POST with the multipart upload. The file is getting uploaded but without the parent folder Id & without a file name. I want to set the file name & file position in my drive. Please help me to solve this issue. Here is my code :

String body = '--not_so_random_boundary\nContent-Type: application/json; charset=utf-8\nContent-Disposition: form-data; name="metadata"\n{"name":"test.txt","mimeType":"text/html","parents":[{"Id":"1pf0OL6YqwzE4nClKDcvQAMhe_rYKGs3o"}]}\n--not_so_random_boundary\nContent-Type: text/plain\nContent-Disposition: form-data; name="file"\n\nThe file data\n--not_so_random_boundary--';

Http http = new Http();
HttpRequest req1 = new HttpRequest();
req1.setEndpoint('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart');
req1.setHeader('Authorization', 'Bearer ' + accesstoken);
//req1.setHeader('Content-Type', 'multipart/related; boundary=--not_so_random_boundary');
//req1.setHeader('Content-length', String.valueOf(body.length()));
req1.setBody(body);
req1.setMethod('POST');

HttpResponse resp1 = http.send(req1);
System.debug(resp1.getBody());

The file is getting created by using this code but with the name 'Untitled' & not in the given folder Id.

Upvotes: 0

Views: 867

Answers (1)

Linda Lawton - DaImTo
Linda Lawton - DaImTo

Reputation: 117254

Upload file data

Create the body of the request. Format the body according to the multipart/related content type [RFC 2387], which contains two parts:

  • Metadata. The metadata must come first and must have a Content-Type header set to application/json; charset=UTF-8. Add the file's metadata in JSON format.
  • Media. The media must come second and must have a Content-Type header of any MIME type. Add the file's data to the media part. Identify each part with a boundary string, preceded by two hyphens. In addition, add two hyphens after the final boundary string.

If you check your body you have the put the metaData second.

Upvotes: 2

Related Questions