2

I am trying to upload files to amazon s3 and I keep on getting FileNotFoundError: [Errno 2] No such file or directory: -filename- error,

init.py

from flask import Flask, render_template, request, redirect
from werkzeug.utils import secure_filename

app = Flask(__name__)

import boto3, botocore
from .config import S3_KEY, S3_SECRET, S3_BUCKET

s3 = boto3.client(
   "s3",
   aws_access_key_id=S3_KEY,
   aws_secret_access_key=S3_SECRET
)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        file = request.files['file']
        filename = ""
        if file:
            filename = secure_filename(file.filename)

        s3.upload_file(Bucket=S3_BUCKET, Filename=filename, Key=filename)
        return redirect(url_for('home.html'))
    return render_template('home.html')

if __name__ == '__main__':
    app.run(debug=True)

config.py

import os

S3_BUCKET                 = os.environ.get("S3_BUCKET")
S3_KEY                    = os.environ.get("S3_KEY")
S3_SECRET                 = os.environ.get("S3_SECRET_ACCESS_KEY")

SECRET_KEY                = os.environ.get('SECRET_KEY')
S3_LOCATION               = 'http://{}.s3-ap-southeast-1.amazonaws.com/'.format(S3_BUCKET)

home.html

{% extends "layout.html" %}
{% block content %}
<div>
    <form method='post' enctype='multipart/form-data'>
        <div class='form-group'>
            <label for='file'> Upload </label>
            <input type='file' id='file' name='file'>
        </div>
        <div class='form-group'>
            <button type='submit' class='btn btn-primary'> Submit </button>
        </div>
    </form>
</div>
{% endblock %}

I have also installed and configured aws cli.

simanacci
  • 2,197
  • 3
  • 26
  • 35
snigcode
  • 365
  • 4
  • 17

2 Answers2

2

FileNotFoundError is due to file does not exist. the code in upload() does not actually save the uploaded file, it merely obtains a safe name for it and immediately tries to open it - which fails.

Try saving the file to the file system using save() after obtaining the safe filename:

upload_file = request.files['file']
filename = secure_filename(upload_file.filename)
upload_file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

and then uploading it (assuming that you've configured an UPLOAD_FOLDER):

with

open(os.path.join(app.config['UPLOAD_FOLDER'], filename), 'rb') as f
AWS PS
  • 4,420
  • 1
  • 9
  • 22
0

Alternatively, you can use upload_fileobj and pass the file object instead, plus it doesn't require file.save().

file = request.files['file']
filename = secure_filename(file.filename)
s3.upload_fileobj(Bucket=S3_BUCKET, Fileobj=file, Key=filename) # Fileobj instead of Filename
simanacci
  • 2,197
  • 3
  • 26
  • 35