2014-05-12 2 views
0

mongoengine 및 Bottle 프레임 워크를 사용하여 이미지 파일을 MongoDB에 업로드해야합니다.Bottle framework과 Mongoengine을 사용하여 MongoDB에 이미지 파일을 업로드하는 방법은 무엇입니까?

Traceback (most recent call last): 
    File "/usr/local/lib/python3.4/dist-packages/mongoengine/fields.py", line 1311, in put 
    img = Image.open(file_obj) 
    File "/usr/lib/python3/dist-packages/PIL/Image.py", line 2000, in open 
    prefix = fp.read(16) 
AttributeError: 'FileUpload' object has no attribute 'read' 

During handling of the above exception, another exception occurred: 

Traceback (most recent call last): 
    File "/usr/local/lib/python3.4/dist-packages/bottle.py", line 862, in _handle 
    return route.call(**args) 
    File "/usr/local/lib/python3.4/dist-packages/bottle.py", line 1728, in wrapper 
    rv = callback(*a, **ka) 
    File "./imgtest.py", line 38, in new_img 
    img.img_src.put(img_src, content_type = 'image/jpeg') 
    File "/usr/local/lib/python3.4/dist-packages/mongoengine/fields.py", line 1314, in put 
    raise ValidationError('Invalid image: %s' % e) 
mongoengine.errors.ValidationError: Invalid image: 'FileUpload' object has no attribute 'read' 

이이 이미지를 업로드 할 수 있습니다 :

<!DOCTYPE html> 
<html> 
<head> 
    <title></title> 
</head> 
<body> 
<form action="/new" method="post" enctype="multipart/form-data"> 
    Image ID: <input type="text" name="id" /> 
    Select a file: <input type="file" name="upload" /> 
    <input type="submit" value="Start upload" /> 
</form> 
</body> 
</html> 

나는 이미지를 업로드하려고, 그것은 오류를 제공합니다

from bottle import Bottle, run, route, post, debug, request, template, response 
from mongoengine import * 


connect('imgtestdb') 


app = Bottle() 


class Image(Document): 
    img_id = IntField() 
    img_src = ImageField() 


@app.route('/img/<image>') 
def get_img(image): 
    img = Image.objects(img_id=image)[0].img_src 
    response.content_type = 'image/jpeg' 

    return img 


@app.route('/new') 
def new_img_form(): 
    return template('new.tpl') 


@app.post('/new') 
def new_img(): 
    img_id = request.forms.get('id') 
    img_src = request.files.get('upload') 

    img = Image() 
    img.img_id = img_id 
    img.img_src.put(img_src, content_type = 'image/jpeg') 
    img.save() 



app.run(host='localhost', port=8080, debug=True, reloader=True) 

그리고 템플릿 : 내 파이썬 코드가있다 Bottle 요청에서 MongoDB로 파일을 보냅니 까?

@app.route('/upload', method='POST') 
def do_upload(): 
    upload = request.files.get('upload') 

    with open('tmp/1.jpg', 'w') as open_file: 
     open_file.write(upload.file.read()) 

오류 :

내가 전에 업로드를 저장 파일 열기를 시도 그리고

ValueError('I/O operation on closed file',) 

:

@app.route('/upload', method='POST') 
def do_upload(): 
    img_id = request.forms.get('imgid') 
    upload = request.files.get('upload') 

    upload.save('tmp/{0}'.format(img_id)) 

그것은 오류 반환 :

난 그냥 파일을 저장하려고
ValueError('read of closed file',) 

내가 뭘 잘못하고 있니?

답변

0

첫 번째 모든 img_src는 bottle.FileUpload 클래스의 인스턴스입니다. read()가 없습니다. 기본적으로 파일을 저장하고 다시 엽니 다. 아래 테스트를하십시오. 행운을 빕니다!

import os 

from bottle import route, run, template, request 
from mongoengine import Document, IntField, ImageField, connect 

connect('bottle') 

class Image(Document): 
    img_id = IntField() 
    img_src = ImageField() 

@route('/home') 
def home(): 
    return template('upload') 

@route('/upload', method='POST') 
def do_upload(): 
    img_id = request.forms.get('id') 
    img_src = request.files.get('upload') 
    name = img_src.filename 

    # your class ... 
    img = Image() 
    img.img_id = img_id 
    # img_src is class bottle.FileUpload it not have read() 
    # you need save the file 
    img_src.save('.') # http://bottlepy.org/docs/dev/_modules/bottle.html#FileUpload 

    # mongoengine uses PIL to open and read the file 
    # https://github.com/python-imaging/Pillow/blob/master/PIL/Image.py#L2103 
    # open temp file 
    f = open(img_src.filename, 'r') 

    # saving in GridFS... 
    img.img_src.put(f) 
    img.save() 

    return 'OK' 

run(host='localhost', port=8080, debug=True) 
+0

Return'ValueError ('닫힌 파일에 대한 입출력 작업',)' –

+0

Ok! 괜찮아! :) 이제 문제는 파일을 처리하는 것입니다. 시도해보십시오. http://stackoverflow.com/questions/18952716/valueerror-i-operation-on-closed-file – horacioibrahim

0

사실이 img_src는 더 .read() 메소드

을 갖지 않는 bottle.FileUpload 인스턴스이지만 다음 img_src.file가 _io.BufferedRandom가 .read 갖도록() 메소드 인 경우.

그래서 당신이 직접 수행 할 수 있습니다

file_h = img_src.file 
img = Image.open(file_h) 

을 여전히 베개 2.5 Image.open()와 함께 열려고이 나에게 준 "ValueError를을 : 폐쇄 파일의 읽기"(예외가 Image.open에서 온 () 및 fp.read (16) 호출)

병을 0.12에서 0.12.7로 업그레이드하면 트릭과이 예외가 사라집니다. 도움이 되길 바랍니다.

관련 문제