Python 将文本框中的字符串和文件一起发送到Flask中
使用flask,我正在呈现html页面,在该页面上我需要上传文件,并同时获取文本字符串,以便与文档一起处理。Python 将文本框中的字符串和文件一起发送到Flask中,python,forms,flask,jinja2,Python,Forms,Flask,Jinja2,使用flask,我正在呈现html页面,在该页面上我需要上传文件,并同时获取文本字符串,以便与文档一起处理。 第一部分,导入和解析文档工作得很好。但我无法在一个请求中同时导入文件和读取文本框。 可能吗 我的app.py: # route and function to handle the upload page @app.route('/', methods=['GET', 'POST']) def upload_page(): if request.method == 'POST':
第一部分,导入和解析文档工作得很好。但我无法在一个请求中同时导入文件和读取文本框。
可能吗 我的app.py:
# route and function to handle the upload page
@app.route('/', methods=['GET', 'POST'])
def upload_page():
if request.method == 'POST':
# check if there is a file in the request
if 'file' not in request.files:
return render_template('upload.html', msg='No file selected')
file = request.files['file']
# if no file is selected
if file.filename == '':
return render_template('upload.html', msg='No file selected')
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(path)
# text input:
text = request.form['text']
processed_text = text
print(text)
# perform analysis on it
My upload.html:
<html>
<head>
<title>Upload Docx</title>
</head>
<body>
<h1>Upload new File</h1>
<form method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
<form method=post>
<input name="text">
<input type="submit">
</form>
{% if msg %}
<h1><p style="color:blue";>{{ msg }} </p></h1>
{% endif %}
{% if file_name %}
<p> Imported document: <b> {{file_name}} </b> </p>
{% endif %}
<h1>Result:</h1>
{% if d_type %}
<p> I. Type of document: <b> {{ d_type }} </b> </p>
{% else %}
The analysis result will be displayed here.
{% endif %}
</body>
</html>
上传Docx
上载新文件
{%if msg%}
{{msg}}
{%endif%}
{%if文件名%}
导入的文档:{{file_name}}
{%endif%}
结果:
{%if d_type%}
一、文件类型:{{d_Type}
{%else%}
分析结果将显示在此处。
{%endif%}
所以,我需要的是有一个文本框,当用户按upload file时,它将被读取。似乎我找到了一个解决方案-将文本框移动到一个带有upload的表单中。不知道是否合法,但似乎有效) 替换此项:
<h1>Upload new File</h1>
<form method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
<form method=post>
<input name="text">
<input type="submit">
</form>
上传新文件
为此:
<h1>Upload new File</h1>
<form method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input name="text">
<input type=submit value=Upload>
</form>
上载新文件
这是非常合法的。这是正确的方法!解决自己问题的伟大工作:)