Flask - 获取上传文件的名称(不带文件扩展名)

11

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

例如: 我有一个名为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')>

现在,我想要更新数据库中 pr1 行的 file 字段,只需要文件名称和文件扩展名即可。如何获取文件名?

2个回答

22

它返回一个FileStorage对象,fFileStorage对象,您可以通过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'
>>> 

应用程序.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 -

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接