Anusha Swaminathan
Anusha Swaminathan

Reputation: 69

Convert google drive picker file to javascript file type

I am using Google API V3. I have a scenario where I use a google drive picker to pick a file (of any extension) from the drive and send it to the server for an operation (cannot mention lot of details due to confidential info related to the project).

Edit: I am trying to pick an mpp file (MS Project) from google drive using the drive picker and send the file to the server. The server converts the MPP file to JSON and returns it back to the client, This is what I am trying to do. I am able to achieve this with a normal input tag, but the requirement is to use google drive picker.

I am able to get the file via picker, get the file details using Google Files API (files.get), but I do not know to proceed further to convert it into a JavaScript File type (similar to the input tag where we upload a file).

    showDrivePicker({
        title: 'Pick an mpp file',
        selectFolderEnabled: true,
        enableMyDrive: true
    }, function pickerCallback( data ) {
        if ( data[google.picker.Response.ACTION] == google.picker.Action.PICKED ) {
            var doc = data[google.picker.Response.DOCUMENTS][0],
                url = doc[google.picker.Document.URL].split('/view'),
                name = doc.name;

            gapi.client.files.get({
                  fileId: 'xxxxx', 
                  corpora: 'teamDrive',
                  supportsTeamDrives: true,
                  includeTeamDriveItems: true,
                  includeTeamDriveItemsRequired: true,
                  includeItemsFromAllDrives: true,
                  fields: '*',
            }).then((response) => {
               // I have the downloadUrl here, but what should I do with it?
            })
        }
    }, me);

Kindly help with this.

Thanks

Upvotes: 1

Views: 801

Answers (1)

Martí
Martí

Reputation: 2851

What you want to do in a situation like this is to:

  1. Download the file from drive
  2. Convert it into a File object

You can download the file by giving the ID and setting alt to media. To create the file you call its constructor with the body of the response, and the filename and MIME type from the original picker document information:

function pickerCallback(data) {
 if (data[google.picker.Response.ACTION] === google.picker.Action.PICKED) {
   const doc = data[google.picker.Response.DOCUMENTS][0]
   gapi.client.drive.files.get({
     fileId: doc.id,
     alt: 'media',
   }).then(function(res) {
     const file = new File([res.body], doc.name, { type: doc.mimeType })
    
     // Do whatever with the file
     console.log(file)
   })
 }
}

References

Upvotes: 2

Related Questions