如何通过flask上传然后下载文件?

时间:2019-06-05 18:20:26

标签: python flask

我准备了一个脚本,其中用户可以上传文件作为输入文件(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>

1 个答案:

答案 0 :(得分:0)

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