在 Flask 中,如何临时存储用户提交的文件以对其进行操作并将其返回? [英] In Flask, how do I store a user submitted file temporarily to manipulate it and return it back?

查看:118
本文介绍了在 Flask 中,如何临时存储用户提交的文件以对其进行操作并将其返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我一直在开发 Flask 应用程序,其中用户将文件提交到表单,服务器接收并操作它,然后将编辑后的文件返回给用户.我是 Flask 和网络开发的新手,所以请耐心等待.我已经使用表单和文件字段设置了网站,但我不确定如何从文件中获取数据.我必须将它存储在服务器上吗?如果我这样做了,我完成后是否必须删除?

So I've been working on a Flask application where the user submits a file to a form, the server takes it and manipulates it, then returns the edited file back to the user. I am new to Flask and web dev in general, so bear with me. I have already set up the website with the form and a filefield, but Im not exactly sure how I can get the data from the file. Do i have to store it on the server? If I do, do I have to delete after im done?

这是我目前的路线

@app.route('/mysite', methods=['post', 'get'])
def mysite():
    form = mysiteform()

    if request.method == 'POST' and form.validate():
        file = form.file.data.read()
        filename = secure_filename(file.filename)
    return render_template('mysite.html', title = 'hello world!', form=form)

推荐答案

在 Flask 官方文档站点,有一个 文件上传示例如下:

In Flask official documentation site, there is a file uploader example as below:

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # If the user does not select a file, the browser submits an
        # empty file without a filename.
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('download_file', name=filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
    '''

您可以通过以下方式获取文件内容:file = request.files['file'] 当然您还可以对文件进行进一步操作.

Here is how you can get the file content: file = request.files['file'] and of course you can do further manipulation on the file.

以下是保存文件的方法file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)).如果您想保存文件并稍后返回文件,或者只是在内存中修改它并立即返回,这完全取决于您.

Here is how you can save the file file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)). It's really up to you if you want to save the file and return the file later or just modify it in memory and return it immediately.

这篇关于在 Flask 中,如何临时存储用户提交的文件以对其进行操作并将其返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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