Google Drive upload file using Google API

12,738

Use Files:insert This method supports an /upload URI and accepts uploaded media. The Official Google Documentation contains examples.

First, POST the new file metadata to the Drive endpoint. It has to be in the form of a File resource JSON object:

POST /drive/v2/files HTTP/1.1
Host: www.googleapis.com
Authorization: Bearer <OAuth 2.0 access token here>
...

{
"title": "file_name.extension",
"mimeType": "mime/type",
"description": "Stuff about the file"
}

The response body will be a JSON representation of the newly created File resource. It will look like:

{
"kind": "drive#file",
"id": string,
"etag": etag,
"selfLink": string,
"title": "file_name",
"mimeType": "mime/type",
"description": "Stuff about the file"
...
"downloadUrl": string,
...
}

This is a confirmation that the file entry has been created. Now you need to upload the content. To do that you need to take the ID of the file given by the id JSON attribute in the response above and PUT the content of the actual file to the upload endpoint with an OAuth 2.0 authorized request. It should look like:

PUT /upload/drive/v2/files/{id}?uploadType=media HTTP/1.1
Host: www.googleapis.com
Authorization: Bearer <OAuth 2.0 access token here>
Content-Type: mime/type

<file content here>

You may also needing Resumable upload, It is especially useful if you are transferring large files and the likelihood of a network interruption or some other transmission failure is high, for example, when uploading from a mobile client app. It can also reduce your bandwidth usage in the event of network failures because you don't have to restart large file uploads from the beginning.

Share:
12,738
Yeep
Author by

Yeep

Updated on June 17, 2022

Comments

  • Yeep
    Yeep almost 2 years

    Based on the link at Google API. I would like to use Multipart upload due to the large file size. But that have alot thing i don't understand. Please Advanced.

    Based on Google API docs, To use simple upload

    POST https://www.googleapis.com/upload/drive/v3/files?uploadType=media
    

    What I'm try is as below but it is not work

    https://www.googleapis.com/upload/drive/v3/C:\Users\RNKP74\Desktop\Full_XML.zip?uploadType=media
    

    From Google REST link, it show the example as below, how to run this?

    POST /upload/drive/v3/files?uploadType=multipart HTTP/1.1
    Host: www.googleapis.com
    Authorization: Bearer your_auth_token
    Content-Type: multipart/related; boundary=foo_bar_baz
    Content-Length: number_of_bytes_in_entire_request_body
    
    --foo_bar_baz
    Content-Type: application/json; charset=UTF-8
    
    {
      "name": "My File"
    }
    
    --foo_bar_baz
    Content-Type: image/jpeg
    
    JPEG data
    --foo_bar_baz--