Search code examples
javascriptfilegoogle-drive-apigoogle-api-js-client

Google Drive API V3 Javascript - Create File with Content


This question has been asked before, but the answer was using API V2. The google documentation does not clarify how to create a file with its content using javascript client code. I tried using the code listed under Node, however, it only creates the file, it does not insert any content. Here is my code:

  let fileMetadata = {
    'name': name,
    parents: [parentId]
  };

  let media = {
    mimeType: 'text/plain',
    body: 'content inside file'
  };

  gapi.client.drive.files.create({
    resource: fileMetadata,
    media,
    fields: 'id'
  })
  .then(response => {
    console.log('response: ', response);
  })
  .catch(() => {
    console.log('something is wrong');
  });

Can someone help me insert content into files please?


Solution

  • How about this sample script? In my environment, although gapi.client.drive.files.create() can create an empty file on Google Drive, it cannot directly upload files including contents. I think that this might not be able to upload files and metadata with the multipart/related, although this might be resolved by the future update. So now, as one of workarounds, I use XMLHttpRequest.

    Before you use this sample script, please confirm the following points.

    • In your situation, you have already been able to create files using gapi. In my script, the access token is retrieved using gapi.
    • When you use this script, please set fileContent and metadata.

    Sample script :

    In this sample script, a text file including contents is created under a folder.

    var fileContent = 'sample text'; // As a sample, upload a text file.
    var file = new Blob([fileContent], {type: 'text/plain'});
    var metadata = {
        'name': 'sampleName', // Filename at Google Drive
        'mimeType': 'text/plain', // mimeType at Google Drive
        'parents': ['### folder ID ###'], // Folder ID at Google Drive
    };
    
    var accessToken = gapi.auth.getToken().access_token; // Here gapi is used for retrieving the access token.
    var form = new FormData();
    form.append('metadata', new Blob([JSON.stringify(metadata)], {type: 'application/json'}));
    form.append('file', file);
    
    var xhr = new XMLHttpRequest();
    xhr.open('post', 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id');
    xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
    xhr.responseType = 'json';
    xhr.onload = () => {
        console.log(xhr.response.id); // Retrieve uploaded file ID.
    };
    xhr.send(form);
    

    Request body :

    In this script, form is as follows. This is sent to Google Drive using the create method of Drive API.

    ------WebKitFormBoundaryxX0XmxgooMjdUECR
    Content-Disposition: form-data; name="metadata"; filename="blob"
    Content-Type: application/json
    
    {"name":"sampleName","mimeType":"text/plain","parents":["#####"]}
    ------WebKitFormBoundaryxX0XmxgooMjdUECR
    Content-Disposition: form-data; name="file"; filename="blob"
    Content-Type: text/plain
    
    sample text
    ------WebKitFormBoundaryxX0XmxgooMjdUECR--
    

    In my environment, I confirmed that this works fine. But if this didn't work in your environment, I'm sorry.