Home > OS >  Why would trying to add metadata to a Google Drive file save it as text?
Why would trying to add metadata to a Google Drive file save it as text?

Time:10-24

I am trying to add the metadata to a file that I previously uploaded to Google Drive (text) the metadata is the title and the description but it happens that when I send the file it does not change its name or anything. but the (metadata) appears added to the content of the text. i.e. it's like it's just updating the text of that file

Code:

$.ajax({
  url: "https://www.googleapis.com/upload/drive/v2/files/---?UploadType=multipart",
  data: {
    title: "name...",
    // other parameters indicated by google
  },
  headers: {
    "Authorization": "Bearer ..."
  },
  contentType: "application/json", //as indicated by google
  type: "PUT",
  success: function () {
    // ...
  }
});

in the Google text file it appears:

title=name...

CodePudding user response:

I believe your goal is as follows.

  • You have a file in your Google Drive.
  • You want to update the filename of the file using Drive API v2 with ajax.
  • Your access token can be used for updating the filename of the file.

In this case, how about the following modification?

Modification points:

  • In order to update the file metadata, please use the endpoint of PUT https://www.googleapis.com/drive/v2/files/fileId.
  • Please use the JSON object of the file metadata as the string value using JSON.stringify().

When these points are reflected in your showing script, it becomes as follows.

Modified script:

$.ajax({
  url: "https://www.googleapis.com/drive/v2/files/{fileId}",
  data: JSON.stringify({title: "name..."}),
  headers: {
    "Authorization": "Bearer ###your access token###",
  },
  contentType: "application/json",
  type: "PUT",
  success: function (data) {
    console.log(data);
  },
  error: function (data) {
    console.log(data);
  }
});
  • If you want to use Drive API v3, please modify the above script as follows.

      $.ajax({
        url: "https://www.googleapis.com/drive/v3/files/{fileId}",
        data: JSON.stringify({name: "name..."}),
        headers: {
          "Authorization": "Bearer ###your access token###",
        },
        contentType: "application/json",
        type: "PATCH",
        success: function (data) {
          console.log(data);
        },
        error: function (data) {
          console.log(data);
        }
      });
    

References:

  • Related