Insert a new file. Try it now or see an example.
This method supports an /upload URI and accepts uploaded media with the following characteristics:
- Maximum file size: 5120GB
- Accepted Media MIME types:
*/*
Note: Specify a valid MIME type, rather than the literal */*
value. The literal */*
is only used to indicate that any valid MIME type can be uploaded.
Apps creating shortcuts with files.insert
must specify the MIME type application/vnd.google-apps.shortcut
.
Apps should specify a file extension in the title
property when inserting files with the API. For example, an operation to insert a JPEG file should specify something like "title": "cat.jpg"
in the metadata.
Subsequent GET
requests include the read-only fileExtension
property populated with the extension originally specified in the title
property. When a Google Drive user requests to download a file, or when the file is downloaded through the sync client, Drive builds a full filename (with extension) based on the title. In cases where the extension is missing, Google Drive attempts to determine the extension based on the file's MIME type.
Request
HTTP request
This method provides media upload functionality through two separate URIs. For more details, see the document on media upload.
- Upload URI, for media upload requests:
POST https://www.googleapis.com/upload/drive/v2/files
- Metadata URI, for metadata-only requests:
POST https://www.googleapis.com/drive/v2/files
Parameters
Parameter name | Value | Description |
---|---|---|
Required query parameters | ||
uploadType |
string |
The type of upload request to the /upload URI. If you
are uploading data (using an /upload URI), this field is
required. If you are creating a metadata-only file, this field is not
required. Additionally, this field is not shown in the "Try this API"
widget because the widget doesn't support data uploads.
Acceptable values are:
|
Optional query parameters | ||
convert |
boolean |
Whether to convert this file to the corresponding Docs Editors format.
(Default: false )
|
enforceSingleParent |
boolean |
Deprecated. Creating files in multiple folders is no longer supported.
(Default: false )
|
includeLabels |
string |
A comma-separated list of IDs of labels to include in the labelInfo part of the response.
|
includePermissionsForView |
string |
Specifies which additional view's permissions to include in the response. Only 'published' is supported. |
ocr |
boolean |
Whether to attempt OCR on .jpg, .png, .gif, or .pdf uploads.
(Default: false )
|
ocrLanguage |
string |
If ocr is true, hints at the language to use. Valid values are BCP 47 codes. |
pinned |
boolean |
Whether to pin the head revision of the uploaded file. A file can have a maximum of 200 pinned revisions.
(Default: false )
|
supportsAllDrives |
boolean |
Whether the requesting application supports both My Drives and shared drives.
(Default: false )
|
supportsTeamDrives |
boolean |
Deprecated use supportsAllDrives instead.
(Default: false )
|
timedTextLanguage |
string |
The language of the timed text. |
timedTextTrackName |
string |
The timed text track name. |
useContentAsIndexableText |
boolean |
Whether to use the content as indexable text.
(Default: false )
|
visibility |
string |
The visibility of the new file. This parameter is only relevant when convert=false.
Acceptable values are:
|
Authorization
This request requires authorization with at least one of the following scopes:
Scope |
---|
https://www.googleapis.com/auth/drive |
https://www.googleapis.com/auth/drive.file |
https://www.googleapis.com/auth/drive.appdata |
https://www.googleapis.com/auth/drive.apps.readonly |
Some scopes are restricted and require a security assessment for your app to use them. For more information, see the authentication and authorization page.
Request body
In the request body, supply a Files resource with the following properties as the metadata. For more information, see the document on media upload.
Property name | Value | Description | Notes |
---|---|---|---|
Optional Properties | |||
contentRestrictions[].readOnly |
boolean |
Whether the content of the file is read-only. If a file is read-only, a new revision of the file may not be added, comments may not be added or modified, and the title of the file may not be modified. | writable |
contentRestrictions[].reason |
string |
Reason for why the content of the file is restricted. This is only mutable on requests that also set readOnly=true . |
writable |
copyRequiresWriterPermission |
boolean |
Whether the options to copy, print, or download this file, should be disabled for readers and commenters. | writable |
description |
string |
A short description of the file. | writable |
folderColorRgb |
string |
Folder color as an RGB hex string if the file is a folder or a shortcut to a folder. The list of supported colors is available in the folderColorPalette field of the About resource. If an unsupported color is specified, it will be changed to the closest color in the palette. | writable |
id |
string |
The ID of the file. | writable |
indexableText.text |
string |
The text to be indexed for this file. | writable |
labels.starred |
boolean |
Whether this file is starred by the user. | writable |
labels.trashed |
boolean |
Whether the file has been trashed, either explicitly or from a trashed parent folder. Only the owner may trash a file. The trashed item is excluded from all files.list responses returned for any user who does not own the file. However, all users with access to the file can see the trashed item metadata in an API response. All users with access can copy, download, export, and share the file. | writable |
labels.viewed |
boolean |
Whether this file has been viewed by this user. | writable |
lastViewedByMeDate |
datetime |
Last time this file was viewed by the user (formatted RFC 3339 timestamp). | writable |
mimeType |
string |
The MIME type of the file. This is only mutable on update when uploading new content. This field can be left blank, and the mimetype will be determined from the uploaded content's MIME type. | writable |
modifiedDate |
datetime |
Last time this file was modified by anyone (formatted RFC 3339 timestamp). This is only mutable on update when the setModifiedDate parameter is set. | writable |
originalFilename |
string |
The original filename of the uploaded content if available, or else the original value of the title field. This is only available for files with binary content in Google Drive. |
writable |
parents[] |
list |
Collection of parent folders which contain this file. If not specified as part of an insert request, the file will be placed directly in the user's My Drive folder. If not specified as part of a copy request, the file will inherit any discoverable parents of the source file. Update requests can also use the |
writable |
properties[] |
list |
The list of properties. | writable |
shortcutDetails.targetId |
string |
The ID of the file that this shortcut points to. | writable |
title |
string |
The title of this file. Note that for immutable items such as the top level folders of shared drives, My Drive root folder, and Application Data folder the title is constant. | writable |
writersCanShare |
boolean |
Whether writers can share the document with other users. Not populated for items in shared drives. | writable |
Response
If successful, this method returns a Files resource in the response body.
Examples
Note: The code examples available for this method do not represent all supported programming languages (see the client libraries page for a list of supported languages).
Java
Uses the Java client library.
import com.google.api.client.http.FileContent; import com.google.api.services.drive.Drive; import com.google.api.services.drive.model.File; import com.google.api.services.drive.model.ParentReference; import java.io.IOException; import java.util.Arrays; // ... public class MyClass { // ... /** * Insert new file. * * @param service Drive API service instance. * @param title Title of the file to insert, including the extension. * @param description Description of the file to insert. * @param parentId Optional parent folder's ID. * @param mimeType MIME type of the file to insert. * @param filename Filename of the file to insert. * @return Inserted file metadata if successful, {@code null} otherwise. */ private static File insertFile(Drive service, String title, String description, String parentId, String mimeType, String filename) { // File's metadata. File body = new File(); body.setTitle(title); body.setDescription(description); body.setMimeType(mimeType); // Set the parent folder. if (parentId != null && parentId.length() > 0) { body.setParents( Arrays.asList(new ParentReference().setId(parentId))); } // File's content. java.io.File fileContent = new java.io.File(filename); FileContent mediaContent = new FileContent(mimeType, fileContent); try { File file = service.files().insert(body, mediaContent).execute(); // Uncomment the following line to print the File ID. // System.out.println("File ID: " + file.getId()); return file; } catch (IOException e) { System.out.println("An error occurred: " + e); return null; } } // ... }
.NET
Uses the .NET client library.
using Google.Apis.Drive.v2; using Google.Apis.Drive.v2.Data; using Google.Apis.Requests; using System.Collections.Generic; using System.Net; // ... public class MyClass { // ... /// <summary> /// Insert new file. /// </summary> /// <param name="service">Drive API service instance.</param> /// <param name="title">Title of the file to insert, including the extension.</param> /// <param name="description">Description of the file to insert.</param> /// <param name="parentId">Parent folder's ID.</param> /// <param name="mimeType">MIME type of the file to insert.</param> /// <param name="filename">Filename of the file to insert.</param> /// <returns>Inserted file metadata, null is returned if an API error occurred.</returns> private static File insertFile(DriveService service, String title, String description, String parentId, String mimeType, String filename) { // File's metadata. File body = new File(); body.Title = title; body.Description = description; body.MimeType = mimeType; // Set the parent folder. if (!String.IsNullOrEmpty(parentId)) { body.Parents = new List<ParentReference>() {new ParentReference() {Id = parentId}}; } // File's content. byte[] byteArray = System.IO.File.ReadAllBytes(filename); MemoryStream stream = new MemoryStream(byteArray); try { FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, mimeType); request.Upload(); File file = request.ResponseBody; // Uncomment the following line to print the File ID. // Console.WriteLine("File ID: " + file.Id); return file; } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); return null; } } //... }
PHP
Uses the PHP client library.
/** * Insert new file. * * @param Google_Service_Drive $service Drive API service instance. * @param string $title Title of the file to insert, including the extension. * @param string $description Description of the file to insert. * @param string $parentId Parent folder's ID. * @param string $mimeType MIME type of the file to insert. * @param string $filename Filename of the file to insert. * @return Google_Service_Drive_DriveFile The file that was inserted. NULL is * returned if an API error occurred. */ function insertFile($service, $title, $description, $parentId, $mimeType, $filename) { $file = new Google_Service_Drive_DriveFile(); $file->setTitle($title); $file->setDescription($description); $file->setMimeType($mimeType); // Set the parent folder. if ($parentId != null) { $parent = new Google_Service_Drive_ParentReference(); $parent->setId($parentId); $file->setParents(array($parent)); } try { $data = file_get_contents($filename); $createdFile = $service->files->insert($file, array( 'data' => $data, 'mimeType' => $mimeType, )); // Uncomment the following line to print the File ID // print 'File ID: %s' % $createdFile->getId(); return $createdFile; } catch (Exception $e) { print "An error occurred: " . $e->getMessage(); } }
Python
Uses the Python client library.
from apiclient import errors from apiclient.http import MediaFileUpload # ... def insert_file(service, title, description, parent_id, mime_type, filename): """Insert new file. Args: service: Drive API service instance. title: Title of the file to insert, including the extension. description: Description of the file to insert. parent_id: Parent folder's ID. mime_type: MIME type of the file to insert. filename: Filename of the file to insert. Returns: Inserted file metadata if successful, None otherwise. """ media_body = MediaFileUpload(filename, mimetype=mime_type, resumable=True) body = { 'title': title, 'description': description, 'mimeType': mime_type } # Set the parent folder. if parent_id: body['parents'] = [{'id': parent_id}] try: file = service.files().insert( body=body, media_body=media_body).execute() # Uncomment the following line to print the File ID # print 'File ID: %s' % file['id'] return file except errors.HttpError, error: print 'An error occurred: %s' % error return None
JavaScript
Uses the JavaScript client library.
/** * Insert new file. * * @param {File} fileData File object to read data from. * @param {Function} callback Function to call when the request is complete. */ function insertFile(fileData, callback) { const boundary = '-------314159265358979323846'; const delimiter = "\r\n--" + boundary + "\r\n"; const close_delim = "\r\n--" + boundary + "--"; var reader = new FileReader(); reader.readAsBinaryString(fileData); reader.onload = function(e) { var contentType = fileData.type || 'application/octet-stream'; var metadata = { 'title': fileData.fileName, 'mimeType': contentType }; var base64Data = btoa(reader.result); var multipartRequestBody = delimiter + 'Content-Type: application/json\r\n\r\n' + JSON.stringify(metadata) + delimiter + 'Content-Type: ' + contentType + '\r\n' + 'Content-Transfer-Encoding: base64\r\n' + '\r\n' + base64Data + close_delim; var request = gapi.client.request({ 'path': '/upload/drive/v2/files', 'method': 'POST', 'params': {'uploadType': 'multipart'}, 'headers': { 'Content-Type': 'multipart/mixed; boundary="' + boundary + '"' }, 'body': multipartRequestBody}); if (!callback) { callback = function(file) { console.log(file) }; } request.execute(callback); } }
Go
Uses the Go client library.
import ( "google.golang.org/drive/v2" "fmt" ) // InsertFile creates a new file in Drive from the given file and details func InsertFile(d *drive.Service, title string, description string, parentId string, mimeType string, filename string) (*drive.File, error) { m, err := os.Open(filename) if err != nil { fmt.Printf("An error occurred: %v\n", err) return nil, err } f := &drive.File{Title: title, Description: description, MimeType: mimeType} if parentId != "" { p := &drive.ParentReference{Id: parentId} f.Parents = []*drive.ParentReference{p} } r, err := d.Files.Insert(f).Media(m).Do() if err != nil { fmt.Printf("An error occurred: %v\n", err) return nil, err } return r, nil }
Objective-C
Uses the Objective-C client library.
#import "GTLDrive.h" // ... + (void)insertFileWithService:(GTLServiceDrive *)service title:(NSString *)title description:(NSString *)description parentId:(NSString *)parentId mimeType:(NSString *)mimeType data:(NSData *)data completionBlock:(void (^)(GTLDriveFile *, NSError *))completionBlock { GTLDriveFile *file = [GTLDriveFile object]; file.title = title; file.descriptionProperty = description; file.mimeType = mimeType; if (parentId != null) { file.parents = [NSArray arrayWithObjects: parentId, nil]; } GTLUploadParameters *uploadParameters = [GTLUploadParameters uploadParametersWithData:data MIMEType:mimeType]; GTLQueryDrive *query = [GTLQueryDrive queryForFilesInsertWithObject:file uploadParameters:uploadParameters]; // queryTicket can be used to track the status of the request, more information can // be found on <a href="https://code.google.com/p/google-api-objectivec-client/wiki/Introduction#Uploading_Files">https://code.google.com/p/google-api-objectivec-client/wiki/Introduction#Uploading_Files</a> GTLServiceTicket *queryTicket = [service executeQuery:query completionHandler:^(GTLServiceTicket *ticket, GTLDriveFile *insertedFile, NSError *error) { if (error == nil) { // Uncomment the following line to print the File ID. // NSLog(@"File ID: %@", insertedFile.identifier); completionBlock(insertedFile, nil); } else { NSLog(@"An error occurred: %@", error); completionBlock(nil, error); } }]; } // ...
Try it!
Note: APIs Explorer currently supports metadata requests only.
Use the APIs Explorer below to call this method on live data and see the response.