Reputation: 804
I have an HTML form (implemented in Flask) for uploading files. And I want to store the uploaded files directly to S3.
The relevant part of the Flask implementation is as follows:
@app.route('/',methods=['GET'])
def index():
return '<form method="post" action="/upload" enctype="multipart/form-data"><input type="file" name="file" /><button>Upload</button></form>'
I then use boto3 to upload the file to S3 as follows:
@app.route('/upload',methods = ['GET','POST'])
def upload_file():
if request.method =='POST':
file = request.files['file']
if file:
filename = secure_filename(file.filename)
#file.save(os.path.join(UPLOAD_FOLDER,filename))
s3_resource = boto3.resource('s3',aws_access_key_id='****',
aws_secret_access_key='*****')
buck = s3_resource.Bucket('MY_BUCKET_NAME')
buck.Object(file.filename).put(Body=file.read())
return 'uploaded'
File is getting uploaded successfully in S3 Bucket. And when trying to open that file it is opening as blank text file. Even I tried to set ContentType
in put()
method but still not working.
Also its size is showing 0B
Please let me know whats going wrong?
Thanks!
Upvotes: 0
Views: 547
Reputation: 1142
You have certainly reached end of stream.
file.read()
has no bytes to read, hence empty file on s3.
Either try file.seek(0)
to reset the stream or you must ensure that you are reading file once.
For example:
# You just read the file here.
file.save(os.path.join(UPLOAD_FOLDER, filename))
# file.read() is empty now, you reached to the end of stream
# You are again reading the file here but file.read() is empty, so reset the stream.
file.seek(0)
# file.read() is back to original now
buck.Object(file.filename).put(Body=file.read())
Upvotes: 3