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

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

问题描述

我正在尝试使用Flask创建一个Web应用程序,让用户上传一个文件并将它们提供给另一个用户。现在,我可以正确地将文件上传到 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)

但它是返回:


找不到

Not Found

在服务器上找不到请求的URL。如果您手动输入了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)

推荐答案

您需要确保传递给目录的值参数是一个绝对路径,更正了您应用程序的当前位置。

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)

重要的是重申 UP LOAD_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天全站免登陆