Google Drive API generates new blank file named 'Untitled' when used with certain browser versions

Trying to utilize the 'browser' version of the Google Drive API, which seems to mostly adhere to Nodejs syntax. However, there are limited examples available beyond the basic hello world example for the browser.

Currently, the goal is to create a folder and then generate a simple JSON config file within that folder as a demonstration. Yet, upon executing the code, only an empty file named 'Untitled' appears in my Google Drive.

Below is a snippet of the file creation process, which returns as successful:

        this.MEM.config = {
            categories : {},
            createdOn : Date.now()
        }

        let fileMetadata = {
            name : 'config.json',
            parents : [this.MEM.parent]
        }

        let media = {
            mimeType : 'application/json',
            body : JSON.stringify(this.MEM.config)
        }

        query = {
            resource: fileMetadata,
            media: media,
            fields: 'id'
        }

        console.log(query);

        try {
            res = await gapi.client.drive.files.create(query);
        } catch(err) {
            throw err;
        }

        console.log(res);

The execution of this code does not result in any errors:

{
  "result": {
    "id": "1OI0ttFr11UH1__XAlSnyUil5hpp6mScB"
  },
  "body": "{\n \"id\": \"1OI0ttFr11UH1__XAlSnyUil5hpp6mScB\"\n}\n",
  "headers": {
    "cache-control": "no-cache, no-store, max-age=0, must-revalidate",
    "content-encoding": "gzip",
    "content-length": "67",
    "content-type": "application/json; charset=UTF-8",
    "date": "Thu, 29 Apr 2021 20:26:13 GMT",
    "expires": "Mon, 01 Jan 1990 00:00:00 GMT",
    "pragma": "no-cache",
    "server": "GSE",
    "vary": "Origin, X-Origin"
  },
  "status": 200,
  "statusText": "OK"
} 

Instead of successfully creating a 'config.json' file within the designated folder with the stringified object, only an Untitled file appears at the root of my Google Drive.

Answer №1

Points of Adjustment:

  • At this stage, it appears that the file content is not included when using gapi.client.drive.files.create. For instance, by utilizing the below query without the file content included, the file can be created using the values from fileMetadata but the file content is omitted.

      query = {
          resource: fileMetadata,
          fields: 'id'
      }
    
  • If you wish to create a new file with the file content included, consider directly sending a request to the endpoint for uploading the file.

Upon modification of your script, it will appear as follows.

Adjusted script:

this.MEM.config = {
  categories: {},
  createdOn: Date.now()
}
let fileMetadata = {
  name: 'config.json',
  parents: [this.MEM.patent]
}
const form = new FormData();
form.append('metadata', new Blob([JSON.stringify(fileMetadata)], {type: 'application/json'}));
form.append('file', new Blob([JSON.stringify(this.MEM.config)], {type: 'application/json'}));
fetch('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id', {
  method: 'POST',
  headers: new Headers({'Authorization': 'Bearer ' + gapi.auth.getToken().access_token}),
  body: form
})
.then((res) => res.json())
.then((res) => console.log(res));
  • Here, the access token is obtained using
    gapi.auth.getToken().access_token
    . As per your query, it seems your access token can be utilized for file uploads.

Note:

  • With this adjustment, both the file and file metadata are uploaded using multipart/form-data, with a maximum content size of 5 MB. Please take note of this limitation.
  • If dealing with large files, consider using resumable uploads. The Javascript library ResumableUploadForGoogleDrive_js may come in handy for this purpose.

References:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Develop a vector and embed it automatically in PHP

I am working on a program that automatically creates vectors based on client input in a function. The function retrieves data from the client, and if the client specifies they are from Tirana City, the function will generate a stack to store and manipula ...

A guide on instantly updating displayed flat/section list elements in React Native

I am in the process of creating a screen called ContactListScreen. The direct child of ContactListScreen is ContactItems, which is a sectionList responsible for rendering each individual ContactItem. However, I have encountered a problem where my ContactIt ...

What is the best way to handle mixed parameter types in Spring MVC when sending data from AngularJS?

I am struggling to pass a json object and a string as parameters to my Java controller. Despite my efforts, I keep receiving url = "" in the controller. What could be causing this issue? Is there a solution to successfully passing these parameters? $ ...

Issue with JSONP success function not being triggered

Here is an example of an Ajax call being made to a different domain: <script> $.ajax({ url: 'url?callback=?', dataType: 'jsonp', success: function (data) { alert(data[0].DeviceName) ...

Utilize Meteor and Mongo to access a nested array object in a template with spacebars

I am trying to populate the content of a textarea by extracting data from a nested array. In my helper function, I have specified the document id and the element id. The goal is to extract the content of the text field from the findOne result and display i ...

The error "clearRect is not defined in javascript" occurs when the property is being called on an undefined object in the JavaScript

I've encountered a similar question before, but unfortunately, the solution provided didn't help me! I'm relatively new to JavaScript and have been struggling with this issue for nearly a day now without success. The structure of my class a ...

Running a function on a specific route within the same file in Node.js - here's how to do it

I am looking to execute a function on a specific route that is defined within the same file. module.exports.controller = function(app) { app.get('/folders/create', createDirectory); } var createDirectory = function(path, name, permissions, v ...

AngularJS attempting to conceal the popup menu upon clicking outside of the designated area

My HTML structure looks like this: <div> <a href="" ng-click="$scope.show_menu = !$scope.show_menu">Options</a> <div class="options_box" ng-show="$scope.show_menu"> <button>Option1</button> ... ...

Having trouble locating the bootstrap import statement

Currently, I am working on a project in Angular where I have defined two styles in the angular.json file - styles.css and node_modules/bootstrap/dist/css/bootstrap.min.css. After running ng serve, it shows that it compiled successfully. However, upon ins ...

Unable to transmit data to CodeIgniter controller through ajax communication

I'm struggling with sending a value from an input element to a Codeigniter controller using ajax. The problem arises because I am using a WYSIWYG editor (summernote), which only allows me to receive the input inside a <script>. However, when I ...

What is causing this error/bug to show up in Angular?

I encountered an error while working on my Angular project that incorporates both front-end and back-end development with Python Flask. Even though the page updates correctly, a database-related error is being displayed in the console. Below are the snippe ...

How is it that this JavaScript task does not trigger an error: const a = (1, 2, 3, 4);

let x = (5, 6, 7, 8); console.log(x); let y = 5, 6, 7, 8; console.log(y); In the example above, x will be assigned a value of 8, while the second line will result in an error. What is the reason behind the success of the first assignment? How does it qua ...

Sharing data between two Angular 2 component TypeScript files

I'm facing a scenario where I have two components that are not directly related as parent and child, but I need to transfer a value from component A to component B. For example: In src/abc/cde/uij/componentA.ts, there is a variable CustomerId = "sss ...

Utilize Google Home to browse through nearby websites and respond to inquiries by incorporating Javascript

Can Google Home be programmed to read from a local webpage and provide answers based on the content of that page through Javascript? ...

Certain images fail to load when the properties are altered

I am facing an issue where the images in my child components do not show up when props are changed, unless the page is manually refreshed. There are no 404 errors for the images, and even when I inspect the image element, I can see the correct image link b ...

Accept two parameters for password change

Is there a way to include two values, one being the selected value and the other a PHP variable, in a dropdown select element's onChange function? For example: <div> <?php $sql4 = "SELECT DISTINCT (color), id ...

What is the process for executing my python scripts with selenium in a web browser?

After developing a Python Selenium script on the Django framework, I am stuck on how to run the test case using the browser. While I can currently execute the test case through the terminal, I am now looking for a way to run the same test case through th ...

Using PHP's include/require method with a dynamic path

Looking for assistance with my issue! Ajax is returning the correct information and displaying it in an 'alert(html)' on 'success'. The PHP code echoes $idName and $path correctly on the carrier page where the code resides. There are no ...

Application utilizing Meteor to connect with external websites or applications

Hey everyone, I'm in the process of developing an application that features a directory of stores. One key requirement is that each store has a unique view created with either Flash or JavaScript. The special view components have already been develope ...

Receiving CORS response from the server for just one of the two API calls

Description of the issue: I am facing a peculiar problem where I am encountering different responses while making two calls to the same API. One call is successful, but the other returns a 504 error. Access to XMLHttpRequest at '' from orig ...