Skip to main content
 首页 » 编程设计

python之在python flask中上传文件

2024年10月24日11Terrylee

我正在尝试将基本文本/csv 文件上传到我的网络应用程序中,该应用程序运行 flask 来处理 http 请求。我试图按照在本地主机上运行的 flask 文档中的婴儿示例 here .但是当我在我的页面上尝试这段代码时,它似乎在上传,但随后挂起,实际上我的 flask 服务器卡住了,我必须关闭终端再试一次……Ctrl+C 甚至不起作用。

我执行run.py:

#!/usr/bin/env python 
from app import app 
 
if __name__ == '__main__': 
    app.run(host='0.0.0.0', port=5000, debug=False, use_reloader=False) 

和app是同目录下的一个目录,其中run.py和下面的__init__.py:

import os 
from flask import Flask 
from werkzeug import secure_filename 
 
#Flask object initialization 
#app flask object has to be created before importing views below 
#because it calls "import app from app" 
UPLOAD_FOLDER = '/csv/upload' 
ALLOWED_EXTENSIONS = set(['txt', 'csv']) 
 
app = Flask(__name__) 
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER 

这是我的 views.py 文件,其中包含我的所有路线:

from flask import render_template, request, redirect, url_for 
from app import app 
import os 
 
#File extension checking 
def allowed_filename(filename): 
    return '.' in filename and filename.rsplit('.',1)[1] in ALLOWED_EXTENSIONS 
 
@app.route('/', methods=['GET', 'POST']) 
@app.route('/index.html', methods=['GET', 'POST']) 
def index(): 
    if request.method == 'POST': 
        submitted_file = request.files['file'] 
        if submitted_file and allowed_filename(submitted_file): 
            filename = secure_filename(submitted_file.filename) 
            submitted_file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) 
            return redirect(url_for('uploaded_file', filename=filename)) 
 
    return ''' 
    <!doctype html> 
    <title>Upload new File</title> 
    <h1>Upload new File</h1> 
    <form action="" method=post enctype=multipart/form-data> 
      <p><input type=file name=file> 
         <input type=submit value=Upload> 
    </form> 
    ''' 

请您参考如下方法:

问题是您向 allowed_filename() 传递了错误的内容。您应该传递 submitted_file.filename 而不是 submitted_file 本身