Python flask上传文件,但不保存和使用

Python flask upload file but do not save and use

我的代码当前接收一个文件,并将其保存到预设目录,但是是否可以仅使用该文件(读取文件)而不保存它?

1
2
3
4
5
6
7
8
9
10
11
12
@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return"yatta"
        else:
            return"file not allowed"

    return render_template("index.html")

我都尝试过

file.read()和file.stream.read(),但其返回值为空。 我确认该文件存在于上载目录中,并且看到该文件不为空。


我知道这已经很过时了,但是为了使人们能够在这里登陆进行类似的查询,这是如果您要保存并在病房之后读取文件。 似乎Werkzeug的FileStorage类(在Flask中处理上传的文件的类)指向每次操作(保存或读取)后的文件末尾。 因此,在执行任何后续操作之前,我们必须将指针上移到文件的开头。 我在下面的答案中使用了python的pandas,因为我通常将csv读入dataframe。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import pandas as pd

@app.route('/', methods=['GET', 'POST'])
    def upload_file():
        if request.method == 'POST':
            file = request.files['file']
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

                ## snippet to read code below
                file.stream.seek(0) # seek to the beginning of file
                myfile = file.file # will point to tempfile itself
                dataframe = pd.read_csv(myfile)
                ## end snippet

                return"yatta"
            else:
                return"file not allowed"

        return render_template("index.html")


调用file.read()之前,请确保没有使用file.save()保存文件。

因此,您的功能将是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            contents = file.read()
            # do something with file contents
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return"yatta"
        else:
            return"file not allowed"

    return render_template("index.html")

希望这可以帮助!