【问题标题】:uploading a image to Google Drive shared folder but can't manage to make the image appear as a jpg in google drive将图像上传到 Google Drive 共享文件夹,但无法使图像在 Google Drive 中显示为 jpg
【发布时间】:2020-03-16 13:44:59
【问题描述】:

我正在使用来自 David Lloyd 响应的 Upload File to Google-drive Teamdrive folder with PyDrive 中的此代码,但在运行他的代码后,我无法将 mimeType 更改为 image/jpg。我试过像这样添加我的代码:

parent_folder_id = 'YYYY'

f = drive.CreateFile({
    'title': 'image.jpg', 'mimeType': 'image/jpg'
    'parents': [{
        'kind': 'drive#fileLink',
        'teamDriveId': team_drive_id,
        'id': parent_folder_id
    }]
})
f.SetContentString("path/image.jpg")

f.Upload(param={'supportsTeamDrives': True})

# where XXXX and YYYY are the team drive and target folder ids found from the end of the URLS when you open them in your browser.

但图片在 Google 云端硬盘中以 PDF 文件的形式上传。

【问题讨论】:

  • 你有没有考虑过使用谷歌提供的Python官方Drive API Client
  • 我尝试使用,但无法使用官方使其工作(我是 GoogleApi 和编程的新手,所以要在通过 PyDrive 学习的 API 中编码,因为我发现在其中编码更容易)。但令我感到沮丧的是,这种 mimetype 在上传到我的云端硬盘时有效,但在共享文件夹中无效。
  • 我已将 mimeType 更改为 image/jpeg。它在谷歌驱动器中显示为图像,但它没有给我预览,当我下载它时说文件已损坏。任何想法可能是造成这种情况的原因吗?

标签: python google-drive-api jpeg mime-types


【解决方案1】:

我会给你这个解决方案,它使用Python Client Library for Drive并修改Drive Python Quickstart的一部分代码。我能够将图像上传到特定文件夹中的共享驱动器,并将 mimeType 从 png 更改为 jpg

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from apiclient.http import MediaFileUpload

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/drive']

def main():
    """Shows basic usage of the Drive v3 API.
    Prints the names and ids of the first 10 files the user has access to.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('drive', 'v3', credentials=creds)
    # This is all the metadata for the file
    file_metadata = {
        "name": "testupload.jpg",
        # My shared Drive id
        "driveId": "you-shared-drive-id",
        "parents": [
            #Folder where the file will be saved
            "folder-id"
        ]
    }
    # This is all the file's data
    media = MediaFileUpload('testupload.png', mimetype='image/jpg')
    # This is all the file's data 
    file_upload = service.files().create(
        supportsAllDrives=True,
        supportsTeamDrives=True,
        body=file_metadata,
        media_body=media
    ).execute()

    print(file_upload)

if __name__ == '__main__':
    main()


【讨论】:

  • 我的代码不理解 MediaFileUpload,即使我下载了 apiclient
  • 我也遇到了令牌验证问题,它与代码位于同一文件夹中
  • 您是否使用 pip 安装了 step 2 中的所有库?尝试使用令牌时抛出了什么错误?
【解决方案2】:

如果您将 SetContentString() 更改为 SetContentFile(),它可以将图像上传到团队驱动器。所以代码看起来像这样:

parent_folder_id = 'YYYY'

f = drive.CreateFile({
    'title': 'image.jpg', 'mimeType': 'image/jpg'
    'parents': [{
        'kind': 'drive#fileLink',
        'teamDriveId': team_drive_id,
        'id': parent_folder_id
    }]
})
f.SetContentFile("path/image.jpg")

f.Upload(param={'supportsTeamDrives': True})

# where XXXX and YYYY are the team drive and target folder ids found from the end of the URLS when you open them in your browser.

【讨论】:

    猜你喜欢
    • 2016-09-30
    • 2021-02-04
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多