我们在项目实训(七)中已经完成了简单的flask应用,但是项目需要一个能够实现功能的接口,因为算法部分还没有确定下来,所以要先实现上传文件和下载文件这俩功能,后期再将算法部分嵌入进去。本篇的代码要和基础结构结合起来看哦~
@app.route('/upload', methods=['POST', 'GET'])
def upload():
if request.method == 'POST':
f = request.files['file']
basepath = os.path.dirname(__file__) # 当前文件所在路径
upload_path = os.path.join(basepath, 'static/uploads',secure_filename(f.filename)) #注意:没有的文件夹一定要先创建,不然会提示没有该路径
f.save(upload_path)
with open("static/uploads/"+f.filename, "r") as f: # 打开文件
data = f.read() # 读取文件
print(data)
#print(f.name)
#print(0)
text_create('log.txt',data)
return redirect(url_for('upload'))
return render_template('upload.html')
当用户进入/upload这个url时,需要手动选择上传一个文件(这了有一个简单的UI,写在upload.html中),之后程序会将上传的文件存放在服务器计算机指定的位置。之后这个程序会在打开这个保存下来的文件并读取其中的内容。(这里只设定了简单的txt文件)随后会使用text_create函数在指定位置生成另一个txt文件,在对源文件内容进行加工后写入。
网页示例:
@app.route('/download', methods=['POST', 'GET'])
def download():
if request.method == 'GET':
print(1)
directory = './processed/'
try:
response = make_response(
send_from_directory(directory, 'log.txt', as_attachment=True))
return response
except Exception as e:
return jsonify({"code": "异常", "message": "{}".format(e)})
return render_template('upload.html')
/download与上面的逻辑相仿:得到get参数之后,就会去往我们储存处理过文本的地方,然后把这个文本作为一个response传回去,这里还加了一个异常报错。
此处是text_create函数:
def text_create(name, msg):
desktop_path = "./processed/" # 新创建的txt文件的存放路径
full_path = desktop_path + name # 也可以创建一个.doc的word文档
file = open(full_path, 'w')
file.write(msg)
file.write('---processed')
# file.close()
此处是upload.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>文件上传示例</h1>
<form action="" enctype='multipart/form-data' method='POST'>
<input type="file" name="file">
<input type="submit" value="上传">
</form>
</body>
</html>