Flask - 获取上传文件的名称减去文件扩展名

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

我有一个表单,可以在多个字段中上传多个文件

例如: 我有一个名为 PR1 的字段,另一个 Pr2 和 PR3, 在每个字段中,我可以上传(或不上传)多个文件,上传端工作正常:

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)

因此使用此方法的结果例如是:

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

此时我想用 file 的名称 + 文件扩展名更新数据库中 pr1 行中的字段 file,我该如何只获取文件名?

它返回一个 FileStorage 对象,f 是一个 FileStorage 对象,您可以从中访问文件名 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)

它打印出来:

untitled.png <class 'werkzeug.datastructures.FileStorage'> untitled
127.0.0.1 - - [01/Nov/2018 18:20:34] "POST /upload HTTP/1.1" 200 -

这是一个实用函数来实现它。它还考虑到文件可能类似于 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]