Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create File with Google Drive Api v3 (javascript)

I want to create a file with content using Google Drive API v3. I have authenticated via OAuth and have the Drive API loaded. Statements like the following work (but produce a file without content):

gapi.client.drive.files.create({
    "name": "settings",
}).execute();

Unfortunately I cannot figure out how to create a file that has a content. I cannot find a JavaScript example using Drive API v3. Are there some special parameters that I need to pass?

For simplicity, assume that I have a String like '{"name":"test"}' that is in JSON format that should be the content of the created file.

like image 399
Geminus Avatar asked Jan 20 '16 16:01

Geminus


People also ask

How do I create a Google Drive folder in Google Drive API?

To create a file in a folder, use the files. create method and specify the folder ID in the parents property of the file. The following code snippet shows how to create a file in a specific folder using a client library: Note: If you're using the older Drive API v2, use the files.


3 Answers

Unfortunately, I have not found an answer using only the google drive api, instead I followed Gerardo's comment and used the google request api. Below is a function that uploads a file to google drive.

var createFileWithJSONContent = function(name,data,callback) {
  const boundary = '-------314159265358979323846';
  const delimiter = "\r\n--" + boundary + "\r\n";
  const close_delim = "\r\n--" + boundary + "--";

  const contentType = 'application/json';

  var metadata = {
      'name': name,
      'mimeType': contentType
    };

    var multipartRequestBody =
        delimiter +
        'Content-Type: application/json\r\n\r\n' +
        JSON.stringify(metadata) +
        delimiter +
        'Content-Type: ' + contentType + '\r\n\r\n' +
        data +
        close_delim;

    var request = gapi.client.request({
        'path': '/upload/drive/v3/files',
        'method': 'POST',
        'params': {'uploadType': 'multipart'},
        'headers': {
          'Content-Type': 'multipart/related; boundary="' + boundary + '"'
        },
        'body': multipartRequestBody});
    if (!callback) {
      callback = function(file) {
        console.log(file)
      };
    }
    request.execute(callback);
}
like image 72
Geminus Avatar answered Oct 20 '22 10:10

Geminus


here is the solution with gapi.client.drive,

var parentId = '';//some parentId of a folder under which to create the new folder
var fileMetadata = {
  'name' : 'New Folder',
  'mimeType' : 'application/vnd.google-apps.folder',
  'parents': [parentId]
};
gapi.client.drive.files.create({
  resource: fileMetadata,
}).then(function(response) {
  switch(response.status){
    case 200:
      var file = response.result;
      console.log('Created Folder Id: ', file.id);
      break;
    default:
      console.log('Error creating the folder, '+response);
      break;
    }
});

you'll need to connect/authorise with either of the following scopes

https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/drive.file

EDIT: it is possible to create google files (doc, sheets and so on) by changing the mimeType from application/vnd.google-apps.folder to one of the supported google mime types. HOWEVER, as of now it not possible to upload any content into created files.

To upload files, use the solution provided by @Geminus. Note you can upload a text file or a csv file and set its content type to google doc or google sheets respectively, and google will attempt to convert it. I have tested this for text -> doc and it works.

like image 39
Aurovrata Avatar answered Oct 20 '22 09:10

Aurovrata


Using gapi.client.drive, it is not possible to upload file content. You can only upload metadata.

Instead it is recommended to work directly with the Google REST API. This solution uses a FormData object to build the multipart form body, which simplifies the implementation, and gapi.auth.getToken() to retrieve the required access token. The solution also works with Google shared drives:

var fileContent = "sample text"; // fileContent can be text, or an Uint8Array, etc.
var file = new Blob([fileContent], {type: "text/plain"});
var metadata = {
    "name": "yourFilename",
    "mimeType": "text/plain",
    "parents": ["folder id or 'root'"], // Google Drive folder id
};

var accessToken = gapi.auth.getToken().access_token;
var form = new FormData();
form.append('metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' }));
form.append('file', file);

fetch("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&supportsAllDrives=true", {
    method: 'POST',
    headers: new Headers({ 'Authorization': 'Bearer ' + accessToken }),
    body: form,
}).then((res) => {
    return res.json();
}).then(function(val) {
    console.log(val);
});
like image 7
Mario Varchmin Avatar answered Oct 20 '22 10:10

Mario Varchmin