简体   繁体   English

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

[英]Image uploading fails using html in bottle framework

I am creating a simple web application, where you can upload your article along with an image, using bottle framework. 我正在创建一个简单的Web应用程序,您可以在这里使用Bottle框架将文章和图像一起上传。 The HTML code for the upload page is: 上传页面的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>

I want to store the article in mongodb database and so, I want to store the image in GridFS. 我想将文章存储在mongodb数据库中,因此,我想将图像存储在GridFS中。 The bottle framework code for the same is: 瓶子框架的代码同样是:

@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"

But when I run this code, I get the following error for the image section: 但是,当我运行此代码时,图像部分出现以下错误:

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'

I have run the exact same code on another machine and it worked perfectly. 我已经在另一台机器上运行了完全相同的代码,并且运行良好。 But on my laptop it fails. 但是在我的笔记本电脑上它失败了。 Thank you in advance. 先感谢您。

For your error, if request.files.get('image') have no index 'image' , it will return None (default behavior of dict.get() . 对于您的错误,如果request.files.get('image')没有索引'image' ,它将返回Nonedict.get()默认行为。

So the next line will fail image.file.read() . 因此,下一行将失败image.file.read()

Ensure your form do really send an image (with your browser webtools). 确保您的表单确实发送了图像(使用您的浏览器网络工具)。

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

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