Blob被创建但文件未被使用SignedURL上传。
创始人
2024-12-22 19:00:24
0

在使用SignedURL上传文件时,如果创建了Blob对象但文件未被使用SignedURL上传,可能是因为以下原因:

  1. 未正确配置Blob的上传路径或属性。
  2. 未正确生成SignedURL或未正确使用SignedURL进行文件上传。

下面是一个示例代码,展示了如何解决这个问题:

from google.cloud import storage
from google.auth import compute_engine

def create_signed_url(bucket_name, blob_name):
    # 创建Blob对象
    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(blob_name)

    # 设置Blob的属性
    blob.content_type = 'application/octet-stream' # 设置文件类型
    blob.cache_control = 'public, max-age=3600' # 设置缓存控制
    blob.metadata = {'custom-key': 'custom-value'} # 设置自定义元数据

    # 生成SignedURL
    credentials = compute_engine.Credentials()
    url = blob.generate_signed_url(
        version='v4',
        credentials=credentials,
        expiration=datetime.timedelta(minutes=15),
        method='PUT'
    )

    return url

def upload_file_with_signed_url(url, file_path):
    # 使用SignedURL上传文件
    with open(file_path, 'rb') as file:
        response = requests.put(url, data=file)

    if response.status_code == 200:
        print('文件上传成功')
    else:
        print('文件上传失败')

# 示例使用
bucket_name = 'your-bucket-name'
blob_name = 'your-blob-name'
file_path = 'path/to/file'

signed_url = create_signed_url(bucket_name, blob_name)
upload_file_with_signed_url(signed_url, file_path)

在上面的示例代码中,create_signed_url函数用于创建Blob对象并生成SignedURL,upload_file_with_signed_url函数用于使用SignedURL上传文件。确保将bucket_nameblob_namefile_path替换为实际的值。

这样,你就可以正确地创建Blob对象,并使用SignedURL将文件上传到Google Cloud Storage中了。

相关内容

热门资讯

安装apache-beam==... 出现此错误可能是因为用户的Python版本太低,而apache-beam==2.34.0需要更高的P...
避免在粘贴双引号时向VS 20... 在粘贴双引号时向VS 2022添加反斜杠的问题通常是由于编辑器的自动转义功能引起的。为了避免这个问题...
Android Recycle... 要在Android RecyclerView中实现滑动卡片效果,可以按照以下步骤进行操作:首先,在项...
omi系统和安卓系统哪个好,揭... OMI系统和安卓系统哪个好?这个问题就像是在问“苹果和橘子哪个更甜”,每个人都有自己的答案。今天,我...
原生ios和安卓系统,原生对比... 亲爱的读者们,你是否曾好奇过,为什么你的iPhone和安卓手机在操作体验上有着天壤之别?今天,就让我...
Android - 无法确定任... 这个错误通常发生在Android项目中,表示编译Debug版本的Java代码时出现了依赖关系问题。下...
Android - NDK 预... 在Android NDK的构建过程中,LOCAL_SRC_FILES只能包含一个项目。如果需要在ND...
Akka生成Actor问题 在Akka框架中,可以使用ActorSystem对象生成Actor。但是,当我们在Actor类中尝试...
Agora-RTC-React... 出现这个错误原因是因为在 React 组件中使用,import AgoraRTC from “ago...
安装了Anaconda之后找不... 在安装Anaconda后,如果找不到Jupyter Notebook,可以尝试以下解决方法:检查环境...