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

Accessing information from JSON files using AJAX

I'm currently working on loading data from a JSON file using AJAX. The file I'm referencing is external-file.json. Within the code snippet provided, there are other unrelated sections. I'm encountering an issue within the getViaAjax function ...

Issue with converting form data to JSON format

Having an issue converting a filled form in HTML to a JSON request for sending to the server via HTTP POST. Despite having a filled form, the JSON request only shows an empty array. Here is the JavaScript snippet: $("#submitSurveyBtn").on("click", functi ...

What causes AngularJS to generate an error when attempting to construct a URL for the src attribute of an iframe?

Recently, I've been working with AngularJS directives and encountered an issue while trying to use an expression in the src attribute of an iframe. The error message I received referenced a URL that didn't provide much insight: http://errors.ang ...

Fill a .js script with moustache.js

I need help with organizing some JavaScript code that needs to access server-side data. I want to keep this code in a separate .js file, but I'm having issues populating it with the necessary server information using moustache. Here is my current setu ...

Executing a custom object function in AngularJS by using the ng-click directive

As I navigate my way through AngularJS, I find myself grappling with the concept of calling a custom method of an object and wonder if there's a simpler approach: https://jsfiddle.net/f4ew9csr/3/ <div ng-app="myApp" ng-controller="myCtrl as myCtr ...

What is the secret to the lightning speed at which this tag is being appended to the DOM?

Have a look at this concise sandbox that mirrors the code provided below: import React, { useState, useEffect } from "react"; import "./styles.css"; export default function App() { let [tag, setTag] = useState(null); function chan ...

The compatibility between Polymer JS and Rails Turbolinks is problematic

Currently, I am facing a challenge in integrating PolymerJs with a Ruby on Rails project that has Turbolinks enabled. The issue arises when I click on a link - the new page loads correctly but my Polymer components do not reinitialize. They appear as if no ...

Module specifier "vue" could not be resolved due to an uncaught TypeError. Remember that relative module specifiers must always begin with "./", "../" or "/"

Looking to create the most basic vuejs Hello World application using separate files. Here is the project setup: start by creating index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> ...

Retrieve the latest entry from a JSON file containing epoch timestamps

Currently, I am in the process of developing an app using angularjs. In my json data, I have timestamps and corresponding values like below: { "dps": { "1455719820": 0, "1455720150": 0, "1455720480": 0, "1455720810": 0, " ...

Node.js with Socket.io causes multiple events to be triggered

Currently, I am in the process of developing a rochambo game using node.js and socket.io. The game works as follows: A player places a bet, which is then sent to all other players. These players can choose a sign and click on 'challenge'. Howeve ...

Simulating Cordova plugin functionality during unit testing

I have a code snippet that I need to test in my controller: $scope.fbLogin = function() { console.log('Start FB login'); facebookConnectPlugin.login(["public_profile", "email", "user_friends"], FacebookServices.fbLoginSuccess, FacebookServic ...

The distinction between storing data and component data becomes apparent when using Vuex in conjunction with a persisted state

Below is my post.js file in the store directory: import axios from 'axios' import createPersistedState from "vuex-persistedstate" export default { namespaced: true, state: { sample_data: 'Welcome!!', l ...

Chosen Dropdown selection - Retrieve/Receive information

One of the challenges I'm facing involves a dropdown list on my web form that contains various dates. My main query is: How can I retrieve data for the selected date from a MySQL database and present it to the user? Additionally, if the chosen date do ...

The message "In Angular, there is no such property as 'data' in the type '{ user: User; session: Session; error: ApiError; }'."

Here is my complete supabase.service.ts code: import { Injectable } from "@angular/core"; import { createClient, SupabaseClient, User } from "@supabase/supabase-js"; import { BehaviorSubject } from "rxjs"; import { envi ...

Transmit information from a JavaScript AJAX function to a JSP page

My current goal involves a user clicking on a link on the home page, let's say /home.jsp. Upon clicking this link, I extract the value and use it to call a RESTful resource that interacts with a database and returns a response. The communication with ...

What is the best location to initialize a fresh instance of the Firebase database?

Is the placement of const db = firebase.database() crucial in a cloud function script? For instance, in a file like index.ts where all my cloud functions are located, should I declare it at the top or within each individual function? const db = firebase. ...

Explore images using Vue.js

Recently I started working with Vue for the first time and I'm using Vue 2.0. Here is the structure of my project: -src - assets --> logo.png - components --> beging.vue In the 'beging.vue' file, I made some changes and adde ...

What are some tips for creating an improved React list container component?

I have a small application that fetches movie data. The component hierarchy is not very complex. The state is stored in App.js and then passed down to the Movies.js component, which simply displays a list of movies in a ul element. Data passing from App.j ...

Error: Firebase Cloud Functions reference issue with FCM

Error Encountered An error occurred with the message: ReferenceError: functions is not defined at Object. (C:\Users\CROWDE~1\AppData\Local\Temp\fbfn_9612Si4u8URDRCrr\index.js:5:21) at Module._compile (modul ...

The attribute 'NameNews' is not recognized in the specified type when running ng build --prod

Definition export interface INewsModule{ IDNews:number; IDCategoery:number; NameNews:string; TopicNews:string; DateNews?:Date; ImageCaption:string; ImageName:string ; } Implementation import { Component, OnInit, Input, I ...