Flask 下载文件 [英] Flask Download a File

查看:28
本文介绍了Flask 下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Flask 创建一个网络应用程序,让用户上传文件并将其提供给另一个用户.现在,我可以正确地将文件上传到 upload_folder.但我似乎找不到让用户下载回来的方法.

I'm trying to create a web app with Flask that lets a user upload a file and serve them to another user. Right now, I can upload the file to the upload_folder correctly. But I can't seem to find a way to let the user download it back.

我正在将文件名的名称存储到数据库中.

I'm storing the name of the filename into a database.

我有一个服务于数据库对象的视图.我也可以删除它们.

I have a view serving the database objects. I can delete them too.

@app.route('/dashboard', methods=['GET', 'POST'])
def dashboard():

    problemes = Probleme.query.all()

    if 'user' not in session:
        return redirect(url_for('login'))

    if request.method == 'POST':
        delete = Probleme.query.filter_by(id=request.form['del_button']).first()
        db.session.delete(delete)
        db.session.commit()
        return redirect(url_for('dashboard'))

    return render_template('dashboard.html', problemes=problemes)

在我的 HTML 中,我有:

In my HTML I have:

<td><a href="{{ url_for('download', filename=probleme.facture) }}">Facture</a></td>

和下载视图:

@app.route('/uploads/<path:filename>', methods=['GET', 'POST'])
def download(filename):
    return send_from_directory(directory=app.config['UPLOAD_FOLDER'], filename=filename)

但它又回来了:

未找到

在服务器上找不到请求的 URL.如果您手动输入网址,请检查拼写并重试.

The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

我只想将文件名链接到对象并让用户下载它(对于同一视图中的每个对象)

I just want to link the filename to the object and let the user download it (For every object in the same view)

推荐答案

您需要确保传递给 directory 参数的值是绝对路径,并针对 current 应用程序的位置.

You need to make sure that the value you pass to the directory argument is an absolute path, corrected for the current location of your application.

最好的方法是将 UPLOAD_FOLDER 配置为相对路径(没有前导斜杠),然后通过添加 current_app.root_path 使其成为绝对路径:

The best way to do this is to configure UPLOAD_FOLDER as a relative path (no leading slash), then make it absolute by prepending current_app.root_path:

@app.route('/uploads/<path:filename>', methods=['GET', 'POST'])
def download(filename):
    uploads = os.path.join(current_app.root_path, app.config['UPLOAD_FOLDER'])
    return send_from_directory(directory=uploads, filename=filename)

重要的是要重申 UPLOAD_FOLDER 必须是相对的才能使其工作,例如不以 / 开头.

It is important to reiterate that UPLOAD_FOLDER must be relative for this to work, e.g. not start with a /.

相对路径可以工作,但过于依赖当前工作目录设置为您的 Flask 代码所在的位置.情况可能并非总是如此.

A relative path could work but relies too much on the current working directory being set to the place where your Flask code lives. This may not always be the case.

这篇关于Flask 下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆