繁体   English   中英

如何将表单中的文本保存到文件中?

[英]How to save text from a form into a file?

我正在制作一个用户能够提交图像文件的网站。 在图像文件下,我希望用户能够在文本框中输入某些内容(例如照片日期、位置等),并将文本表单中的图像和文本放入同一个文件中. 这怎么可能? 目前我正在使用 flask_upload 让用户将图像提交到我计算机上的文件夹中。

from flask import Flask, render_template, url_for, request
from flask_uploads import UploadSet, configure_uploads, IMAGES

app = Flask(__name__)

photos = UploadSet('photos', IMAGES)
app.config['UPLOADED_PHOTOS_DEST'] = 'photoup'
configure_uploads(app, photos)


@app.route("/")
def home():
    return render_template("index.html")

@app.route('/upload', methods=['GET', 'POST'])
def upload():
    if request.method == 'POST' and 'photo' in request.files:
        filename = photos.save(request.files['photo'])
        return redirect(url_for('description'))
    return render_template('upload.html')
      

if __name__ == "__main__":
    app.run(debug=True)
<html>
<head>
    <title>Upload</title>
</head>
<body>
<form method=POST enctype=multipart/form-data action="{{ url_for('upload') }}">
    <input type=file name=photo>
    <input type="submit">
</form>
</body>
</html>

所以我尝试用 flask_uploads 做一个例子,但它似乎与 Werkzeug 兼容存在问题。 似乎最后一个有效的版本是 Werkzeug==0.16.0。 我在这个 SO 答案中找到了这个: flask_uploads: ImportError: cannot import name 'secure_filename'


编辑

所以环顾四周,我还在这里找到了“Grey Li”的GitHub回购

在评论部分,他们确认 flask_uploads 仅适用于 werkzeug==0.16.1 版本。

然而,一种解决方案是安装 Flask-Reuploaded Here 我可以尝试一下,并使用 flask_uploads 将我的 GitHub 应用程序与我的应用程序的另一个版本一起上传


已经说过,我使用 flask、flask_sqlalchemy(使用 sqlite3)、html 和 Bootstrap 准备了一个迷你应用程序,它正在执行您所要求的操作。

你可以在这里找到完整的代码(我会用更安全的文件上传来更新它),因为这里给出的只是一小部分:

完整代码

长话短说,这是回答您问题的最重要部分:

## Initiate the database, configs and Picture table for the databse ##

# Built-in Imports
import os
from datetime import datetime
from base64 import b64encode
import base64
from io import BytesIO #Converts data from Database into bytes

# Flask
from flask import Flask, render_template, request, flash, redirect, url_for, send_file # Converst bytes into a file for downloads

# FLask SQLAlchemy, Database
from flask_sqlalchemy import SQLAlchemy


basedir = 'sqlite:///' + os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data.sqlite')

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = basedir
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'dev'
db = SQLAlchemy(app)

# Picture table. By default the table name is filecontent
class FileContent(db.Model):

    """ 
    The first time the app runs you need to create the table. In Python
    terminal import db, Then run db.create_all()
    """
    """ ___tablename__ = 'yourchoice' """ # You can override the default table name

    id = db.Column(db.Integer,  primary_key=True)
    name = db.Column(db.String(128), nullable=False)
    data = db.Column(db.LargeBinary, nullable=False) #Actual data, needed for Download
    rendered_data = db.Column(db.Text, nullable=False)#Data to render the pic in browser
    text = db.Column(db.Text)
    location = db.Column(db.String(64))
    pic_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    def __repr__(self):
        return f'Pic Name: {self.name} Data: {self.data} text: {self.text} created on: {self.pic_date} location: {self.location}'

索引路线

# Index It routes to index.html where the upload forms is 
@app.route('/index', methods=['GET', 'POST'])
@app.route('/')
def index():

    return render_template('index.html')

索引 HTML 与表格

<form method="POST" action="/upload" enctype="multipart/form-data">
        <!-- File Upload-->
        <div class="form-group">
            <label for="inputFile">File input</label>
            <input class="form-control-file" type="file" name="inputFile">
        </div>

        <!-- Location -->
        <div class="form-group">
            <label for="location">Location</label>
            <input class="form-control" type="text" name="location">
        </div>

        <!-- Text -->
        <div class="form-group">
            <label for="text">Write Text</label>
            <textarea class="form-control" name="text" id="text" rows="5" placeholder="Add a Description"></textarea>
        </div>

        <!-- Submit -->        
        <button type="submit" class="btn btn-primary">Submit</button>
    </form>

上传路线,这里是图片发送到数据库并使用正确数据处理的地方

# Render the pics, this Function converts the data from request.files['inputFile'] so that in can be displayed
def render_picture(data):
    
    render_pic = base64.b64encode(data).decode('ascii') 
    return render_pic

# Upload
@app.route('/upload', methods=['POST'])
def upload():

    file = request.files['inputFile']
    data = file.read()
    render_file = render_picture(data)
    text = request.form['text']
    location = request.form['location']

    newFile = FileContent(name=file.filename, data=data, rendered_data=render_file, text=text, location=location)
    db.session.add(newFile)
    db.session.commit() 
    flash(f'Pic {newFile.name} uploaded Text: {newFile.text} Location: {newFile.location}')
    return render_template('upload.html')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM