【问题标题】:Image uploading fails using html in bottle framework在瓶子框架中使用 html 上传图片失败
【发布时间】:2015-10-15 18:28:59
【问题描述】:

我正在创建一个简单的 Web 应用程序,您可以在其中使用瓶子框架上传您的文章和图片。上传页面的HTML代码是:

<html>
    <body>
        <form action="/created" method="POST" encrypt="multipart/form-data">
            Title: <input type="text" name="title"><br>
            Body: <textarea rows = 10 name="body"></textarea><br>
            Choose image: <input type="file" name="image" ><br>
            <input type="submit" >
        </form>
    </body>
</html>

我想将文章存储在 mongodb 数据库中,因此,我想将图像存储在 GridFS 中。同样的瓶子框架代码是:

@post("/created")
def created():
    connect = pymongo.MongoClient(server_address)
    db = connect.practiceB3
    articles = db.articles

    title = request.forms.get('title')
    body = request.forms.get('body')


    fs = gridfs.GridFS(db)
    image = request.files.get('image')
    img_content = image.file.read()
    img_name = image.filename

    document = { "title":title,"body":body}

    articles.insert(document)

    fs.put(img_content,filename = img_name)
    return "Article successfully stored"

但是当我运行这段代码时,我得到图像部分的以下错误:

Error: 500 Internal Server Error

Sorry, the requested URL 'http://localhost:8080/created.html' caused an error:

Internal Server Error

Exception:

AttributeError("'NoneType' object has no attribute 'file'",)

Traceback:

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/bottle.py", line 862, in _handle
    return route.call(**args)
  File "/usr/local/lib/python2.7/dist-packages/bottle.py", line 1732, in wrapper
    rv = callback(*a, **ka)
  File "blogger.py", line 70, in created
    img_content = image.file.read()
AttributeError: 'NoneType' object has no attribute 'file'

我在另一台机器上运行了完全相同的代码,它运行良好。但在我的笔记本电脑上它失败了。提前谢谢你。

【问题讨论】:

  • 有趣的是,您的代码中有img_content = image.file.read(),而您的错误归咎于img_content = image.files.read() ...注意s
  • @Cyrbil 感谢您注意到这一点。我不小心上传了我在进行实验以将“文件”更改为“文件”时遇到的错误,以防万一确保后者是错误的。

标签: python html mongodb bottle gridfs


【解决方案1】:

对于您的错误,如果request.files.get('image') 没有索引'image',它将返回Nonedict.get() 的默认行为。

所以下一行将失败image.file.read()

确保您的表单确实发送了图像(使用您的浏览器网络工具)。

【讨论】:

  • 谢谢伙计。这有帮助。我通过 firefox 的 Web 控制台检查了文件是否通过,我注意到在我的 HTML 表单中,它应该是 enctype = multipart/form-data 而不是我上面输入的那个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-30
  • 2020-11-09
  • 2020-08-29
  • 2016-08-21
  • 2014-10-25
相关资源
最近更新 更多