Guide to acquiring the webViewLink using Google Drive Api v3?

I'm having trouble locating the webViewLink. The documentation (https://developers.google.com/drive/api/v3/reference/files) states that I should receive this parameter when requesting gapi.client.drive.files.list(). However, I don't even have a client object! It seems like my approach might have been wrong from the start. I found a potential solution in an article, but the documentation doesn't provide clear instructions on how to proceed.

  mounted () {
   const gDrive = document.createElement('script')
    gDrive.setAttribute('type', 'text/javascript')
    gDrive.setAttribute('src', 'https://apis.google.com/js/api.js')
    document.head.appendChild(gDrive)
  },

  methods: {
   async pickerDialog () {
      await window.gapi.load('auth2', () => {
        window.gapi.auth2.authorize(
          {
            client_id: this.clientId,
            scope: this.scope,
            immediate: false
          },
          this.handleAuthResult
        )
      })

      window.gapi.load('picker', () => {
        this.pickerApiLoaded = true
        this.createPicker()
      })
    },

    handleAuthResult (authResult) {
      if (authResult && !authResult.error) {
        this.oauthToken = authResult.access_token
        this.createPicker()
      }
    },

    createPicker () {
      if (this.pickerApiLoaded && this.oauthToken) {
        var picker = new window.google.picker.PickerBuilder()
          .enableFeature(window.google.picker.Feature.MULTISELECT_ENABLED)
          .addView(window.google.picker.ViewId.DOCS)
          .setOAuthToken(this.oauthToken)
          .setDeveloperKey(this.apiKey)
          .setCallback(this.pickerCallback)
          .build()

        picker.setVisible(true)
      }
    },

    async pickerCallback (data) {
      if (data[window.google.picker.Response.ACTION] === window.google.picker.Action.PICKED) {
        const docs = data.docs
        const attachments = []
        for (let i = 0; i < docs.length; i++) {
          const attachment = {}
          attachment._id = docs[i].id
          this.$axios.get(`https://www.googleapis.com/drive/v3/files/${attachment._id}`, {
            headers: {
              Authorization: `Bearer ${this.oauthToken}`
            }
          }).then(res => console.log(res))

          attachment.title = docs[i].name
          attachment.name = docs[i].name + '.' + docs[i].mimeType.split('/')[1]
          attachment.type = 'gDrive'
          attachment.description = 'Shared with GDrive'
          attachment.extension =
            '.' +
            docs[i].mimeType.substring(docs[i].mimeType.lastIndexOf('.') + 1)
          attachment.iconURL = docs[i].iconUrl
          attachment.size = docs[i].sizeBytes
          attachment.user = JSON.parse(localStorage.getItem('user'))
          attachment.thumb = null
          attachment.thumb_list = null
          attachments.push(attachment)
        }
        this.tempAttachments = [...attachments]
      }
      this.oauthToken = null
      this.pickerApiLoaded = false
    }
  }
}

Answer №1

When making a list request, be sure to specify the properties fields

In this scenario:

 return gapi.client.drive.files.list({
      "fields": "files/webViewLink"
    })

To make a gapi.client.drive.files.list() request - please refer to the quickstart for Drive API which is provided for client-side Javascript and node.js among others.

Another method to retrieve the webViewLink - if you have the fileId and it suits vue.js better, would be to hardcode it as

 var webcontentlink = ' https://docs.google.com/uc?id='+fileId+'&export=download'

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

Creating a dropdown menu using React库

The API response I received looks like this:- [ { "Product.Name": "Data Migration - Test1", "Product.Id": "8ad0", "Product.Hello__c": { "Value": "First ...

Next.JS: The Key to Long-Term Data Storage

How can we retrieve and maintain data during app initialization or user login so that it persists throughout the application? Currently, every time a page is refreshed, the context is cleared and attempting to use getServerSideProps results in undefined ...

Is it possible to identify the beginning of a download using Selenium?

Currently, I am using Python and Selenium to download a large batch of files. To ensure that each file is successfully downloaded, I am implementing a basic time.sleep() function, but I want to enhance efficiency and guarantee the completion of each downlo ...

Use regular expressions to locate all closing HTML tags and all opening HTML tags individually

My JavaScript function is currently filtering strings by removing all HTML tags. However, I have now realized that I need to perform two separate operations: first, replacing all closing tags with <br>, and then removing all opening tags. return Str ...

A guide on sharing an express.js response object with a different module

In my server.js file, I am attempting to pass an Express response object to a different module. Here is how I have implemented it: const room = require('../controller/rooms_controller') app.post('/rooms', function(req, res){ var na ...

Guide on crafting a scrollable and touch-responsive grid using CSS and JavaScript

I am seeking guidance on creating a grid with a variable number of columns and rows. It should be contained within a separate div and should not interfere with other objects or alter the parent's size. The grid needs to be square and I am currently u ...

Using NodeJS to Send JSON Data via HTTP POST Request

Issue with Sending JSON Data via Http Post in NodeJS const http = require('http'); const fs = require('fs'); var options = { hostname: 'www.postcatcher.in', port: 80, path: '/catchers/5531b7faacde130300002495&apo ...

Getting latitude and longitude from Google Maps in a React Native appHere are the steps to

Looking to retrieve the latitude and longitude from Google using React Native. As a newcomer to React Native, I have been unable to find any resources to address this issue. Any assistance would be greatly appreciated. Thanks! Thanks ...

Automated Star/Stop feature with a convenient Save button (the Start/Stop format will display as mm/dd/yyyy hh:mm:ss)

I'm having an issue with the date format in my code. Currently, it displays as Mon Mar 13 2017 19:02:50 GMT-0400 (Eastern Daylight Time), but I need it to be in the format mm/dd/yyyy 00:00:00 am/pm. My challenge is to capture the current date and tim ...

Tips for extracting dynamically loaded content from a website using Node.js and Selenium?

I'm currently encountering some challenges when trying to scrape a website that utilizes react for certain parts of its content, and I'm unsure about the reason behind my inability to extract the data. Below is the HTML structure of the website: ...

Ways to revert to the initial state in React.js

Check out my codeSandbox project here: https://codesandbox.io/s/bold-lederberg-d2h508?file=/src/Components/Products/Products.js I'm having trouble getting the items back to their original presentation when clicking on "default" - sorting by price wor ...

An error was thrown due to an unexpected end of JSON input while fetching from localhost

After running the code snippet provided, I encountered an Uncaught SyntaxError: Unexpected end of JSON input. As a beginner in coding, any guidance or assistance would be greatly appreciated. Thank you. fetch('http://localhost:3000/add-user', { ...

Guide to iterating through an array within an object in Vue.js

Can someone help me with looping through data fetched from an API using a GET request in Vue.js? This is the sample response obtained: "data": { "Orders": [ { "OrderID": 1, "Ordered_Products": { ...

increasing the size of the JSON object

I have a function that is being called multiple times utilizing jQuery to fetch different JSON data from an API. My aim is to calculate the total count of a specific portion of the JSON retrieved. Below is an example of what I currently have: getTheData( ...

What steps can I take to make my animation work in the opposite direction as well?

I'm currently working with an angular slider that is set to TRUE/OPEN by default. The issue I am facing is that while I am able to slide it using angular animations in one direction, I am unable to see the transition when sliding it back. Any assistan ...

PHP form submission upon conditions being satisfied

I am not utilizing Javascript as it is disabled in my current environment. Here is the code that I would like you to review. I am attempting to use PHP to replicate the functionality of Javascript or jQuery's simple : document.form2.submit() <div ...

Unable to configure AngularJS inputs to have a blank default value

I am facing a peculiar issue where I am unable to initialize my input fields as blank/empty. Even after clearing the cache and performing a hard reload, Google Chrome seems to be auto-populating them with older cached values. Here is the current view: Th ...

Google Scripts: Generating a set of data to include in an email

As a newcomer to Google Script and JavaScript, I'm on a mission to email a list of file names extracted from a spreadsheet. The names reside in a column within my sheet, and after defining a variable called "newfiles" to cherry-pick only the necessary ...

Developing custom events in an NPM package

Developing a basic npm package with signalr integration has been my recent project. Here's how it works: First, the user installs the package Then, the package establishes a connection using signalr At a certain point, the server triggers a function ...

Exploring HTML5 video playback in AngularJS

When I use this code: <video id="video" class="video-js vjs-default-skin" controls width="640" height="264"> <source src="http://localhost:3000/files/public/photos/Let-her-go.mp4" type='video/mp4' /> <p class="v ...