【问题标题】:How can I upload and then download a file through flask?如何通过烧瓶上传然后下载文件?
【发布时间】:2019-06-05 18:20:26
【问题描述】:

我准备了一个脚本,用户可以在其中上传一个文件作为输入文件 (text.dat),然后在将其导入函数 (compute) 后,用户可以下载另一个文件作为输出 (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>

【问题讨论】:

  • 你似乎没有在任何地方打电话给tes
  • 展开。我没有看到任何实际尝试检索函数 tes... tes 似乎会返回文件。
  • 当我排除第一部分(html)下载作品时,上传不。
  • 嗯,是的,现在您在同一个 URL 上有两个函数。那是不可能的;你为什么要这样做?
  • 所以。如何发送输出文件?

标签: python flask


【解决方案1】:

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

【讨论】:

  • 我可以将两者放在同一条路线上吗?我的意思是第二个和第三个。
  • 你可以,但为什么呢?分开更干净。您需要将'GET' 添加到methodshandleFileUpload() 中,然后添加if request.method=='GET':(以及一个用于POST)以确定要在函数中执行的代码。
  • 我更改了 tes() 的路由,但服务器仍然无法向我发送输出(server.log),而上传工作正常并获取并保存在服务器上的文件。
猜你喜欢
  • 2016-07-26
  • 2014-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-18
  • 2021-06-09
  • 2020-08-30
  • 2021-07-15
相关资源
最近更新 更多