在 Bottle 框架中使用 html 上传图片失败

Image uploading fails using html in bottle framework

我正在创建一个简单的 Web 应用程序,您可以在其中使用 Bottle 框架上传您的文章和图片。上传页面的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'

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

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

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

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