在Python中,你可以使用`google-cloud-storage`库来上传和下载图片到Google Cloud Storage。以下是一个简单的示例,展示了如何上传图片到存储桶,并获取一个带有签名URL的链接以供下载。
首先,你需要安装`google-cloud-storage`库:
```bash
pip install google-cloud-storage
```
然后,你可以使用以下代码来上传和下载图片:
```python
from google.cloud import storage
import os
# 初始化Google Cloud Storage客户端
storage_client = storage.Client()
# 指定存储桶名称和要上传的图片文件路径
bucket_name = 'your-bucket-name'
source_file_name = '/path/to/your/image.jpg'
destination_blob_name = 'folder/in/bucket/image.jpg'
# 上传图片到存储桶
def upload_blob(bucket_name, source_file_name, destination_blob_name):
"""Uploads a file to the bucket."""
blob = storage_client.bucket(bucket_name).blob(destination_blob_name)
# 上传文件内容到Blob
with open(source_file_name, "rb") as source_file:
blob.upload_from_file(source_file)
print(f"File {source_file_name} uploaded to {destination_blob_name}.")
# 下载图片从存储桶
def download_blob(bucket_name, source_blob_name, destination_file_name):
"""Downloads a blob from the bucket."""
blob = storage_client.bucket(bucket_name).blob(source_blob_name)
# 从Blob下载文件内容到指定路径
with open(destination_file_name, "wb") as destination_file:
blob.download_to_file(destination_file)
print(f"Blob {source_blob_name} downloaded to {destination_file_name}.")
# 上传图片
upload_blob(bucket_name, source_file_name, destination_blob_name)
# 获取带有签名URL的链接以供下载
def generate_signed_url(bucket_name, blob_name, expiration=3600):
"""Generates a signed URL for accessing the specified blob.
Args:
bucket_name (str): The Google Cloud Storage bucket name.
blob_name (str): The blob name.
Returns:
str: The signed URL.
"""
client = storage.Client()
bucket = client.get_bucket(bucket_name)
blob = bucket.blob(blob_name)
# 生成带有签名URL的链接
url = blob.generate_signed_url(version="v4", expiration=expiration)
return url
# 获取并打印签名URL
signed_url = generate_signed_url(bucket_name, destination_blob_name)
print(f"Signed URL: {signed_url}")
# 如果需要下载图片,可以使用以下代码:
# download_blob(bucket_name, destination_blob_name, '/path/to/download/image.jpg')
```
注意:在实际应用中,你需要替换`your-bucket-name`和`/path/to/your/image.jpg`等变量为你的实际存储桶名称和图片文件路径。同时,你也可以根据需要调整签名URL的过期时间。