I'm new with s3 and trying to upload some files but the I'm getting The system cannot find the file specified: <hashed_file_name>.jpg I understand the issue. When the file is saved at the root, everything is fine. But I don't want to save the file. I want to upload it directly after the action at the form.
def upload_to_s3(file_to_upload, s3_upload_folder):
s3 = boto3.resource('s3',
aws_access_key_id=app.config['ACCESS_KEY_ID'],
aws_secret_access_key=app.config['SECRET_ACCESS_KEY'])
s3.meta.client.upload_file(file_to_upload, app.config['BUCKET_NAME'], s3_upload_folder)
def _user_img_folder(form, file_name):
username = session['name']
vacation_name = slugify(form.test_name.data)
directory = os.path.join(username, test_name)
directory = os.path.join(UPLOAD_FOLDER, directory)
return directory + '/' + file_name
@app.route('/post', methods=['GET', 'POST'])
def test():
if _is_image():
uploaded_images = request.files.getlist('photo')
for image in uploaded_images:
processed_image_name = _hash_image_name(image) # Returns hashed filename with extension
directory = _user_img_folder(form, processed_image_name)
upload_to_s3(str(processed_image_name), str(directory))
return render_template('test.html', form=form, error=error)
Thank you for your help.
EDIT 1:
{# Heavily edited #}
{% extends '_base.html' %}
{% block content %}
<form class="logVacation" enctype=multipart/form-data role="form" method="post" action="/post">
{{ form.csrf_token }}
{{ form.vacation_name(placeholder="Name Your Vacation")}}
<br>
{{ form.location(placeholder="Where was it?") }}
<br>
{{ form.with_who(placeholder='Who was with you') }}
<br><br>
{{ form.description(placeholder="Tell us about your vacation... or not.") }}<br>
{{ form.when(class="datepicker", placeholder="when?") }}
<br><br>
{{ form.photo(multiple="multiple") }}
<br>
<button class="btn btn-sm btn-success" value="upload" type="submit">Done</button>
</form>
{% endblock %}
Found the answer:
I've changed the
s3.meta.client.upload_file(file_to_upload, app.config['BUCKET_NAME'], s3_upload_folder)
to:
s3.Object(app.config['BUCKET_NAME'], s3_upload_folder).put(Body=image)
so the trick is, you must either have the file on disk and provide filepath with file_to_upload OR provide the file itself as I demonstrated in this answer.