在使用SignedURL上传文件时,如果创建了Blob对象但文件未被使用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_name
、blob_name
和file_path
替换为实际的值。
这样,你就可以正确地创建Blob对象,并使用SignedURL将文件上传到Google Cloud Storage中了。