[Google :: Apis :: DriveV3]获取上传的文件URL

问题描述 投票:0回答:1

我想使用Rails中的'google_drive'gem将URL上传到Google云端硬盘。

我试图从创建的返回值中获取该值,但是除了API链接之外没有其他链接,因此您无法访问Google云端硬盘。

是否有获取该链接的方法?

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

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-rails ruby google-api google-drive-api rubygems
1个回答
0
投票
  • 上传文件并获取驱动器ID后,可以使用方法Files: get来获取file resource

  • 文件资源包含文件的所有元数据,如documentation

  • 对您有用,例如webContentLinkwebViewLink

  • 两者均可通过在fields方法中的drive.files.get中指定它们来获得
© www.soinside.com 2019 - 2024. All rights reserved.