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

Viewed 14044

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?

2 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 -

Here is an utility function to achieve it. It also takes into account the fact that the file could be something like file.file.txt

def get_file_name_without_extension(file: UploadFile) -> str:
    filename_parts = file.filename.split('.')
    if (len(filename_parts) > 2):
        name_parts = [filename_parts[i] for i in range(len(filename_parts) - 1)]
        return ".".join(name_parts)
    return filename_parts[0]

Related