0

How can I restrict uploads to Flask to only permit .csv files to be uploaded? I have been trying but can't do it.

So far I have managed to block ALL FILES or upload all of them. I need upload only .csv files.

This is what I have tried:

UPLOAD_FOLDER = "/Users/osito/Desktop/efisys-git/efisys/Webb_App/static/archivos"
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

ALLOWED_EXTENSIONS = set(['csv'])

def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route("/carga", methods=["GET", "POST"])
def carga():
if request.method == "POST":  
archivo = request.form['archivo']  
    if archivo.filename == "":
        flash(u"NO selected file", 'error')
    if not allowed_files(archivo.filename):
        flash(u'only csv files', 'error')                                              

    return redirect(request.url)  
return render_template('home.html')

And this is the HTML..

<input id="upload" type="file" name="file" onchange="readURL();"/>
<form action="/carga" method="POST" enctype="multipart/form-data">
    <h2>Suba Aquí su Archivo CSV </h2>
    <div class="form-group area">
        <input type="hidden" class="form-control" name="archivo" id="archivo">
    </div>
    <button type="submit" name="archivo" class="btn btn primary">Subir</button>
</form>

2 Answers2

0

You can check this article out might help :D

https://flask.palletsprojects.com/en/1.1.x/patterns/fileuploads/

There is an example which allows you to specify allowed extensions

ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}

So try to replace it with one input which is csv in your case

xfat7i
  • 11
  • 1
0

A condition like this might do the trick:

if filename.rsplit('.', 1)[1].lower()=='csv':
# >>> process file here <<<

EDIT: In the meantime I see you have added some more code. You have a function named allowed_file. But you are calling allowed_files further down:

if not allowed_files(archivo.filename):
        flash(u'only csv files', 'error')

Is that where you are going wrong or is it just a typo in the question?

0buz
  • 3,443
  • 2
  • 8
  • 29
  • Thank you.. it just a typo... but i solved the problem with this..... if filename.rsplit('.', 1)[1].lower()=='csv': # >>> process file here <<< Thak you so much –  Feb 11 '20 at 18:42
  • No worries. If it solved the problem, please close the question by marking this answer as Accepted. – 0buz Feb 12 '20 at 10:12