首页 > 解决方案 > 如何通过烧瓶上传然后下载文件?

问题描述

我准备了一个脚本,用户可以在其中上传一个文件作为输入文件(text.dat),然后在将其导入函数(计算)后,用户可以下载另一个文件作为输出(server.log)。

但该脚本无法正常工作 - 它请求输入文件但最终无法下载。

import os
from flask import Flask, request, render_template, url_for, redirect, send_file, 
from compute import compute

app = Flask(__name__)




@app.route("/")
def fileFrontPage():
    return render_template('fileform.html')

@app.route("/handleUpload", methods=['GET','POST'])
def handleFileUpload():
    if 'photo' in request.files:
        photo = request.files['photo']
        if photo.filename != '':            
            photo.save(os.path.join('/home/Documents/web', photo.filename))

    return redirect(url_for('fileFrontPage'))

@app.route('/download', methods = ['GET', 'POST'])   
def tes():  
  with open("/home/Documents/web/download/server.log", "w") as fd, open('/home/Documents/web/text.dat', 'r') as out:
    path = "server.log"
    for i in out:
        s = compute(float(i))
        fd.write("{} \n".format(s))
  return send_file('/home/Documents/web/download/server.log',as_attachment=True, attachment_filename='server.log')


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)

我的html文件如下:

<html>
    <head>
        <title>Simple file upload using Python Flask</title>
    </head>
    <body>        


        <form action="/handleUpload" method="post" enctype="multipart/form-data">
            Choose the file: <input type="file" name="photo"/><BR>
                <input type="submit" value="Upload"/>
        </form> 
    </body>
</html>

标签: pythonflask

解决方案


将路线更改为tes()与 不冲突的内容fileFrontPage(),例如@app.route('/download')


推荐阅读