欢迎访问宙启技术站
智能推送

如何使用googleapiclient.http模块上传文件到Google云存储

发布时间:2024-01-09 05:07:48

要使用googleapiclient.http模块上传文件到Google云存储,需要先安装Google API库。以下是一个示例代码,展示如何使用googleapiclient.http模块上传文件到Google云存储。

首先,您需要使用pip安装所需的库:

pip install google-api-python-client google-auth google-auth-oauthlib google-auth-httplib2

然后,您需要在Google云平台上创建一个服务账号,并将其授权为您的云存储项目。

接下来,创建一个名为upload_file_to_gcs.py的Python文件,并将以下代码复制到文件中:

from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
from google.oauth2.service_account import Credentials

def upload_file_to_gcs(service_account_file, bucket_name, file_path, destination_blob_name):
    credentials = Credentials.from_service_account_file(service_account_file)
    service = build('storage', 'v1', credentials=credentials)

    media = MediaFileUpload(file_path, mimetype='application/octet-stream')
    request = service.objects().insert(bucket=bucket_name, name=destination_blob_name, media_body=media)
    response = request.execute()

    print('File uploaded successfully.')

然后,在同一目录下创建一个名为credentials.json的JSON文件,将您的服务账号的凭据复制到该文件中。

最后,您可以调用upload_file_to_gcs函数,并传入参数来上传文件。

upload_file_to_gcs('credentials.json', 'your-bucket-name', 'file-to-upload.txt', 'destination-blob-name')

确保将'credentials.json'替换为您的凭据文件路径,将'your-bucket-name'替换为您的云存储桶的名称,将'file-to-upload.txt'替换为您要上传的文件路径,并将'destination-blob-name'替换为您想要在云存储中存储的文件名。

运行上述代码后,它将打印出'File uploaded successfully.',表示文件已成功上传到Google云存储中。

这就是使用googleapiclient.http模块上传文件到Google云存储的基本步骤和示例代码。您可以根据自己的需求进行修改和扩展。