Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask - Get the name of an uploaded file minus the file extension

I have a form where I upload multiple files in multiple field

For example: I have a field called PR1, another Pr2 and PR3, In each this fields I can upload(or not) multiple files, the upload side works just fine:

files = request.files
for prodotti in files:
        print(prodotti)
        for f in request.files.getlist(prodotti):
            if prodotti == 'file_ordine':
                os.makedirs(os.path.join(app.instance_path, 'file_ordini'), exist_ok=True)
                f.save(os.path.join(app.instance_path, 'file_ordini', secure_filename(f.filename)))
                print(f)

so with this method the result for example is:

Pr1
<FileStorage: 'FAIL #2.mp3' ('audio/mp3')>

at this point I want to Update the field file in the row of pr1 in my database with just the name of the file + the file extension, how can I get just the name of the file?

like image 276
alessandro buffoli Avatar asked Nov 01 '18 09:11

alessandro buffoli


People also ask

How do I find the name of my uploaded file in flask?

1 Answer. Show activity on this post. Once you fetch the actual file with file = request. files['file'] , you can get the filename with file.

How do you handle uploaded files in flask?

Handling file upload in Flask is very easy. It needs an HTML form with its enctype attribute set to 'multipart/form-data', posting the file to a URL. The URL handler fetches file from request. files[] object and saves it to the desired location.


1 Answers

It's returning a FileStorage object, f is a FileStorage object from which you can access the file's name as FileStorage.filename

>>> from werkzeug.datastructures import FileStorage
>>> f = FileStorage(filename='Untitled.png')
>>> type(f)
<class 'werkzeug.datastructures.FileStorage'>
>>> f.filename
'Untitled.png'
>>> f.filename.split('.')
['Untitled', 'png']
>>> f.filename.split('.')[0]
'Untitled'
>>> 

app.py

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

app = Flask(__name__)

app.config['SECRET_KEY'] = '^%huYtFd90;90jjj'
app.config['UPLOADED_PHOTOS'] = 'static'


@app.route('/upload', methods=['GET', 'POST'])
def upload():
    if request.method == 'POST' and 'photo' in request.files:
        file = request.files['photo']
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOADED_PHOTOS'], filename))
        print(file.filename, type(file), file.filename.split('.')[0])
    return render_template('page.html')


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

It prints out:

untitled.png <class 'werkzeug.datastructures.FileStorage'> untitled
127.0.0.1 - - [01/Nov/2018 18:20:34] "POST /upload HTTP/1.1" 200 -
like image 142
simanacci Avatar answered Oct 29 '22 05:10

simanacci