如何使用Flask读取数据中的单个文件 [英] How to read single file in my data using Flask
本文介绍了如何使用Flask读取数据中的单个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Flask的新手,我想获取已在我的上传路径中上传的单个文件.然后,我想阅读并在hr标签后将其发送到我的html.我该怎么办?
I'm new in Flask, I want to take single file that have been uploaded in my upload path. Then i want to read and send it to my html after hr tag. How can i do that?
这是我的代码:
import os
from flask import Flask, render_template, request, redirect, url_for, abort, \
send_from_directory
from werkzeug.utils import secure_filename
app = Flask(__name__)
app.config['UPLOAD_EXTENSIONS'] = ['.txt', '.doc']
app.config['UPLOAD_PATH'] = 'uploads'
@app.route('/')
def home():
files = os.listdir(app.config['UPLOAD_PATH'])
return render_template('home.html', content=files)
@app.route('/', methods=['POST'])
def upload_file():
uploaded_file = request.files['file']
filename = secure_filename(uploaded_file.filename)
if filename != '':
file_ext = os.path.splitext(filename)[1]
if file_ext not in app.config['UPLOAD_EXTENSIONS']:
abort(400)
uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'], filename))
return redirect(url_for('home'))
if __name__ == "__main__":
app.run()
这是我的HTML页面:
And This one is my HTML Page:
<!doctype html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<h1>File Upload</h1>
<form method="POST" action="" enctype="multipart/form-data">
<p><input type="file" name="file"></p>
<p><input type="submit" value="Submit"></p>
</form>
<hr>
{{ content }}
</body>
</html>
它保存了数据,但由于使用了此代码,所以我无法访问数据files = os.listdir(app.config['UPLOAD_PATH'])
It saves the data, but I can't access the data since I use this codefiles = os.listdir(app.config['UPLOAD_PATH'])
推荐答案
- 您需要一个可变路径,该路径将接受
@app.route('/<filename:filename>')
之类的文件名. - 然后,您需要从上载目录(如
file_path = os.path.join('UPLOAD_PATH', filename)
)中获取具有该名称的文件. - 然后,您需要读取该文件的内容并将其传递到视图中.
- You need a variable route that will accept the a filename like
@app.route('/<filename:filename>')
. - You then need to get the file with that name from your upload directory like
file_path = os.path.join('UPLOAD_PATH', filename)
. - Then you need to read the contents of that file and pass it into your view.
with open(file_path) as file:
content = file.read()
- 然后,您可以在HTML文件中访问它并显示它.
<p>{{ content }}</p>
这是我描述的路线的完整示例:
Here is a complete example of the route I described:
@app.route('/<filename:filename>')
def display_file(filename):
file_path = os.path.join('UPLOAD_PATH', filename)
with open(file_path) as file:
content = file.read()
return render_template('display_file.html', content=content)
这篇关于如何使用Flask读取数据中的单个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文