我正在尝试使用Python和XML API将文件上传到Google云端存储。虽然它上传了一些小文件(例如head -c 50K /dev/urandom > my_file
),但是当我尝试上传更大的文件(例如head -c 100K /dev/urandom > my_file
)时,我从XML API获得以下响应:
<Error>
<Code>AccessDenied</Code>
<Message>Access denied.</Message>
<Details>
Anonymous users does not have storage.objects.create access to bucket [MY_DEFAULT_BUCKET].appspot.com.
</Details>
</Error>
如何使用XML API将大文件上传到Google云端存储?
我的代码如下:
# main.py
import logging
from flask import Flask, render_template, request, url_for
from google.appengine.api import app_identity
from google.cloud import storage
app = Flask(__name__)
client = storage.Client()
bucket_name = app_identity.get_default_gcs_bucket_name()
bucket = client.bucket(bucket_name)
@app.route('/')
def home():
acl = 'public-read'
success_action_redirect = url_for('success', _external=True)
conditions = [
['starts-with', '$key', ''],
{'acl': acl},
{'success_action_redirect': success_action_redirect}]
policy = bucket.generate_upload_policy(conditions)
return render_template('form.html',
bucket_name=bucket_name,
policy_items=policy.items(),
acl=acl,
success_action_redirect=success_action_redirect)
@app.route('/success')
def success():
bucket_name = request.args['bucket']
key = request.args['key']
etag = request.args['etag']
bucket = client.bucket(bucket_name)
blob = bucket.blob(key)
return render_template('success.html',
bucket_name=bucket_name,
key=key,
etag=etag,
public_url=blob.public_url)
@app.errorhandler(500)
def server_error(e):
logging.exception('An error occurred during a request.')
return 'An internal error occurred.', 500
<!-- form.html -->
<!DOCTYPE html>
<meta charset="utf-8">
<title>Upload a File</title>
<h1>Upload a File</h1>
<form action="http://{{bucket_name}}.storage.googleapis.com" method="post"
enctype="multipart/form-data">
<input type="text" name="key" value="my-test-key">
<input type="hidden" name="acl" value="{{acl}}">
<input type="hidden" name="success_action_redirect"
value="{{success_action_redirect}}">
<input name="file" type="file">
<input type="submit" value="Upload">
{% for key, value in policy_items %}
<input type="hidden" name="{{key}}" value="{{value}}">
{% endfor %}
</form>
我还授权App Engine应用默认服务帐户上传到默认存储桶:
$ gsutil acl ch -u [YOUR_PROJECT_ID]@appspot.gserviceaccount.com:O gs://[YOUR_DEFAULT_BUCKET_NAME]