如何将文件上传到 Heroku 托管的网站?

How to upload a file to your website hosted by Heroku?

我开发了一个网站,可以获取用户提供的文件并从中提取相关数据,我使用 Python/Flask 作为后端,网站存储在 Heroku 中。

该应用程序在我的本地计算机上运行良好,但是当我在 Heroku 中 运行 它时,每当我尝试 upload/process 一个文件时,我都会在 Heroku 的日志中收到此消息:

2022-02-14T17:27:48.000421+00:00 app[web.1]: FileNotFoundError: [Errno 2] No such file or directory: '/application/uploads/report.html'

我的 python 绕过文件上传的代码是:

app.config['UPLOAD_PATH'] = './application/uploads'

@app.route('/read', methods=['GET', 'POST'])
def read():
    form = ReadForm()
    if form.validate_on_submit():
        if request.method == 'POST':
            files = request.files.getlist('read')
            for file in files:
                if file and allowed_file(file.filename):
                    filename = secure_filename(file.filename)
                    file.save(os.path.join(app.config['UPLOAD_PATH'], filename))
            return redirect(url_for('show'))
    return render_template('read.html', form=form)

How do I make the uploaded files available to my application? After reading the file, the application just delete it.

我在这里看到一个标题与我的非常相似的问题: How to upload file on website hosted by Heroku?

其中一个答案建议使用亚马逊的 S3,这是唯一的解决方案吗?

@buran 向我指出了另一个 post 帮助我解决了问题:

我在路径定义中添加了以下内容:

base_path = os.path.dirname(__file__)

所以最后一个是:

# Path for the files upload part
app.config['UPLOAD_PATH'] = '/uploads'
base_path = os.path.dirname(__file__)

然后上传文件的时候我参考的路径是这样的:

if file and allowed_file(file.filename):
    filename = secure_filename(file.filename)
    file.save(os.path.join(base_path + "/" + app.config['UPLOAD_PATH'], filename))

所以,而不是:

file.save(os.path.join(app.config['UPLOAD_PATH'], filename))

我用过:

file.save(os.path.join(base_path + "/" + app.config['UPLOAD_PATH'], filename))