首页 > 解决方案 > [Google::Apis::DriveV3 ]获取上传文件地址

问题描述

我想获取使用 rails 中的 'google_drive' gem 上传到 Google Drive 的 URL。

我试图从创建的返回值中获取它,但没有这样的链接,而是 API 链接,因此您无法访问 Google Drive。

有没有获取该链接的方法?

这是返回的链接,不是这个

https://www.googleapis.com/drive/v3/files/1m4Ja7qCNrfqhrkrtKibuPoV02Shp5w7G2?

我要这个

https://drive.google.com/drive/u/0/folders/1ObHbN1heqwewgx1RkyEJ1Bm4GL3TSTjmI

谢谢你。

require "google/apis/drive_v3"
require "googleauth"
require "googleauth/stores/file_token_store"
require "fileutils"

OOB_URI = "urn:ietf:wg:oauth:2.0:oob".freeze
APPLICATION_NAME = "upload-image-to-gdrive".freeze
CREDENTIALS_PATH = "credentials.json".freeze
TOKEN_PATH = "token.yaml".freeze
SCOPE = Google::Apis::DriveV3::AUTH_DRIVE


class DriveUploader
  def initialize
    # Initialize the API
    @@drive = Google::Apis::DriveV3
    @@service = @@drive::DriveService.new
    @@service.client_options.application_name = APPLICATION_NAME
    @@service.authorization = authorize
  end

  def authorize
    client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH
    token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH
    authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store
    user_id = "default"
    credentials = authorizer.get_credentials user_id
    credentials
  end

  def upload(name, image_source)
    file_metadata = {
        name: name,
        parents: ['1ObHbN11jdig94x1RkyEJ1Bm4GL3TSTjmI'] # Drive ID
    }
    file = @@service.create_file(
        file_metadata,
        fields: 'id',
        upload_source: image_source,
        #content_type: 'image/jpeg' # 'application/pdf'
        content_type: 'application/pdf' # 'application/pdf'
    )
    user_permission = {type: 'anyone', role: 'reader'}
    @@service.create_permission(file.id, user_permission, fields: 'id')
    file
  end
end

标签: ruby-on-railsrubygoogle-apigoogle-drive-apirubygems

解决方案


  • 将文件上传到您的驱动器并检索其 Id 后,您可以使用方法Files: get以获取file resource.

  • 文件资源包含文件的所有元数据,如文档中所述

  • 对您有用的可能是 thewebContentLink或 thewebViewLink

  • 两者都可以通过fieldsdrive.files.get方法中指定它们来获得

推荐阅读