繁体   English   中英

使用Flask将文件上传到Google云端存储

[英]Uploading files to Google Cloud Storage with Flask

我正在尝试使用Flask通过App Engine实例将一些图像上传到GCS,但每次上传文件时,当我下载它时,我都会收到一个损坏的文件。 我究竟做错了什么 ?

我已经按照文档的方式下载并使用了Google云端存储客户端。

@app.route('/upload', methods=['POST'])
def upload():
    if request.method == 'POST':
        file = request.files['file']
        extension = secure_filename(file.filename).rsplit('.', 1)[1]
        options = {}
        options['retry_params'] = gcs.RetryParams(backoff_factor=1.1)
        options['content_type'] = 'image/' + extension
        bucket_name = "gcs-tester-app"
        path = '/' + bucket_name + '/' + str(secure_filename(file.filename))
        if file and allowed_file(file.filename):
            try:
                with gcs.open(path, 'w', **options) as f:
                    f.write(str(file))
                    print jsonify({"success": True})
                return jsonify({"success": True})
            except Exception as e:
                logging.exception(e)
                return jsonify({"success": False})

谢谢你的帮助 !!

您正在上传(写入gcs流)文件对象的str表示,而不是文件内容。

试试这个:

@app.route('/upload', methods=['POST'])
def upload():
    if request.method == 'POST':
        file = request.files['file']
        extension = secure_filename(file.filename).rsplit('.', 1)[1]
        options = {}
        options['retry_params'] = gcs.RetryParams(backoff_factor=1.1)
        options['content_type'] = 'image/' + extension
        bucket_name = "gcs-tester-app"
        path = '/' + bucket_name + '/' + str(secure_filename(file.filename))
        if file and allowed_file(file.filename):
            try:
                with gcs.open(path, 'w', **options) as f:
                    f.write(file.stream.read())# instead of f.write(str(file))
                    print jsonify({"success": True})
                return jsonify({"success": True})
            except Exception as e:
                logging.exception(e)
                return jsonify({"success": False})

但这不是最有效的方法,而且,直接来自应用引擎的文件上传量为32mb上限,避免这种情况的方法是通过使用GCS签署上传URL并直接从前端上传文件到GCS,或者您可以使用blobstore和处理程序创建文件上传URL以执行上传后处理,如下所示: https//cloud.google.com/appengine/docs/python/blobstore/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM