Skip to content

Instantly share code, notes, and snippets.

@merqurio
Created October 14, 2014 08:43
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save merqurio/c0b62eb1e1769317907f to your computer and use it in GitHub Desktop.
Save merqurio/c0b62eb1e1769317907f to your computer and use it in GitHub Desktop.
Flask image file upload with Google App Engine (GAE) Blobstore Example, with Google Cloud Storage (GCS)
# Render the template for the upload form:
@app.route("/upload")
def upload():
uploadUri = blobstore.create_upload_url('/submit', gs_bucket_name=BUCKET_NAME)
return render_template('upload.html', uploadUri=uploadUri)
# Place your uploadUri in the form path (html):
'''<form action="{{ uploadUri }}" method="POST" enctype="multipart/form-data">'''
# Here is the function to handle the upload of the image (I return the blob_key for practical reasons, replace it with your template):
@app.route("/submit", methods=['POST'])
def submit():
if request.method == 'POST':
f = request.files['file']
header = f.headers['Content-Type']
parsed_header = parse_options_header(header)
blob_key = parsed_header[1]['blob-key']
return blob_key
# Now say you serve your images with a path like this:
# /img/imagefilename
# Then your image serving function is :
@app.route("/img/<bkey>")
def img(bkey):
blob_info = blobstore.get(bkey)
response = make_response(blob_info.open().read())
response.headers['Content-Type'] = blob_info.content_type
return response
# Finally, anywhere you need to display an image in a template, you simply put the code:
'''<img src="/img/{{ bkey }} />'''
@roesler-stan
Copy link

So helpful, thank you! I couldn't find a Flask solution anywhere!

@perses76
Copy link

Thank you!!!

@daisy200029
Copy link

Thanks for sharing!

@mrbabbage
Copy link

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment