【问题标题】:How to store uploaded file in mongoDB in Flask?如何将上传的文件存储在 Flask 中的 mongoDB 中?
【发布时间】:2014-11-20 02:15:16
【问题描述】:

在我的Flask 项目中,我试图让文件上传与 MongoDB 一起工作。从this upload tutorial 获得灵感我设法上传了一个文件并将其存储在文件系统中。使用 these mongoengine docs 我现在也想将它存储在 MongoDB 中。

我当前的文档定义如下:

class UserDocument(mongoDb.Document):
    created = mongoDb.DateTimeField(default=datetime.utcnow, required=True)
    filename = mongoDb.StringField()
    _file = mongoDb.FileField()

我上传并存储了一个具有以下视图的文件:

@app.route('/upload', methods=['GET', 'POST'])
def mytickets():
    if request.method == 'POST':
        file = request.files['file']
        if file and isAllowedFile(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))  # This works!
            userDoc = UserDocument()
            userDoc.filename = filename
            userDoc._file.put(file, content_type=file.content_type)
            userDoc.save()
        else:
            return 'We don\'t allow this file extension.'

    return render_template('upload.html')

文件是在文件系统中创建的,所以有一个文件。在命令行我验证了MongoDB中有一个文档,但是_file的内容似乎是空的:

>>> UserDocument.objects.count()
1
>>> d = UserDocument.objects.first()
>>> d._file.read()
''

我想可能是你不能在命令行上显示图像数据,所以我想知道如何再次通过 Flask 显示文档。为此,我制作了一个简单的 Flask 视图来显示一个文件:

@app.route('/show')
def showSomething():
    doc = UserDocument.objects.first()
    return doc._file.read()

这不会返回任何东西,要么是因为文件永远不会被写入 MongoDB,要么是因为我的 showSomething 不正确,或者两者兼而有之。

有人知道我在这里做错了什么吗?欢迎所有提示!

[编辑] 我尝试读取文件的内容并将其添加到文档中。这让我更进一步(见下文),因为 read() 现在输出一些十六进制的东西。问题是我不明白从文件中读取它并从 Flask 文件上传中获取它有什么不同。最后;有没有一种简单的方法可以使用 Flask 在浏览器中显示输出?

>>> from app.documents import UserDocument
>>> UserDocument.objects.count()
0
>>> f = open('/Users/kramer65/repos/tc/app/static/uploads/IMG_7599.JPG', 'r')  # I'm on MacOSX, so 'rb' doesn't exist
>>> userdoc = UserDocument()
>>> userdoc.filename = 'blabla.jpg'
>>> userdoc._file.put(f, content_type='image/jpeg')
>>> userdoc.save()
<UserDocument: UserDocument object>
>>> UserDocument.objects.count()
1
>>> d = UserDocument.objects.first()
>>> d._file.read()
'\xff\xd8\xff\xe1%\xfeExif\x00\x00II*\x00\x08\x00\x00\x00\t\x00\x0f etc. etc.'
>>> d._file.read()
''  # Why oh why is it the second time suddenly an empty string?!

【问题讨论】:

  • 你有没有尝试打开刚刚用'rb'模式保存的文件并把它交给put方法?
  • @Dragu - 感谢您的提示。我尝试了您的建议并将结果添加到我上面的问题中。这似乎做了一些事情,但是 read() 方法仍然输出一个空字符串。还有什么想法吗?
  • @Dragu - 我在我的问题中编辑了我的编辑,因为我现在从.read() 获得了一些十六进制输出。奇怪的是,我第二次调用.read()(见上文)时它没有输出任何内容。任何进一步的想法可能吗? :S
  • 不知道为什么 read() 只工作一次。我认为您必须检查它在 mongoengine 的源代码上的工作方式:)

标签: python mongodb file-upload flask


【解决方案1】:

read() 第二次返回空字符串,因为第一次已经读取并返回了全部内容。

【讨论】:

    猜你喜欢
    • 2014-05-20
    • 2020-08-24
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2012-02-16
    相关资源
    最近更新 更多