下载图像数据然后上传到 Google 云存储

Download image data then upload to Google Cloud Storage

我有一个 运行 在 Google AppEngine 上的 Flask 网络应用程序。该应用程序有一个表单,我的用户将使用该表单来提供图像 links。我想从 link 下载图像数据,然后将其上传到 Google Cloud Storage 存储桶。

到目前为止,我在 Google 的文档中找到的内容告诉我使用 'cloudstorage' 客户端库,我已安装并导入为 'gcs'。
在这里找到:https://cloud.google.com/appengine/docs/python/googlecloudstorageclient/read-write-to-cloud-storage

我想我没有通过请求正确处理图像数据。我从 Cloud Storage 上传调用返回了一个 200 代码,但是当我在控制台中查找它时没有对象。这是我尝试检索图像然后上传的地方:

img_resp = requests.get(image_link, stream=True)
objectName = '/myBucket/testObject.jpg'

gcs_file = gcs.open(objectName,
                    'w',
                    content_type='image/jpeg')
gcs_file.write(img_resp)
gcs_file.close()

编辑: 这是我更新的代码以反映答案的建议:

image_url = urlopen(url)
content_type = image_url.headers['Content-Type']
img_bytes = image_url.read()
image_url.close()

filename = bucketName + objectName
options = {'x-goog-acl': 'public-read',
           'Cache-Control': 'private, max-age=0, no-transform'}

with gcs.open(filename,
              'w',
              content_type=content_type,
              options=options) as f:
    f.write(img_bytes)
    f.close()

但是,我仍然在 POST(创建文件)调用中​​收到 201 响应,然后在 PUT 调用中收到 200 响应,但该对象从未出现在控制台中。

试试这个:

from google.appengine.api import images
import urllib2

image = urllib2.urlopen(image_url)

img_resp = image.read()
image.close()

objectName = '/myBucket/testObject.jpg'
options = {'x-goog-acl': 'public-read', 
         'Cache-Control': 'private, max-age=0, no-transform'}

with gcs.open(objectName,
              'w',
              content_type='image/jpeg', 
              options=options) as f:

    f.write(img_resp)
    f.close()

而且,为什么要限制他们只输入 url。为什么不允许他们上传本地图片:

if isinstance(image_or_url, basestring):    # should be url
    if not image_or_url.startswith('http'):
        image_or_url = ''.join([ 'http://', image_or_url])
    image = urllib2.urlopen(image_url)
    content_type =  image.headers['Content-Type']
    img_resp = image.read()
    image.close()
else:
    img_resp = image_or_url.read()
    content_type = image_or_url.content_type

如果您 运行 在开发服务器上,文件将上传到您的本地数据存储区。在以下位置查看:

http://localhost:<your admin port number>/datastore?kind=__GsFileInfo__

http://localhost:<your admin port number>/datastore?kind=__BlobInfo__