2013-11-14 3 views
2

Я использую основные WTFormsFileField до сих пор я могу загрузить файл, но его не получить хранится в каталогах, но его получения хранится в базе данных PostGreSQL в <Binary data>. Как сохранить его в каталогах и отобразить в браузере. Я не уверен, что я делаю это правильно. Я просто хочу загрузить изображения и отобразить их в браузере, вот и все.Сохранение загруженного изображения?

Статья Модель

class Article(Base): 
    __tablename__ = 'articles' 
    id = Column(Integer, primary_key=True) 
    title = Column(String(255), unique=True, nullable=False) 
    body = Column(Text, default=u'') 
    image_field = Column(BYTEA) 
    category_id = Column(Integer, ForeignKey(Category.id)) 
    category = relationship(Category) 
    created = Column(DateTime, default=datetime.datetime.utcnow) 
    edited = Column(DateTime, default=datetime.datetime.utcnow) 

    @classmethod 
    def all(cls): 
     return DBSession.query(Article).order_by(sa.desc(Article.created)) 

    @classmethod 
    def by_id(cls, id): 
     return DBSession.query(Article).filter(Article.id == id).first() 

    @property 
    def slug(self): 
     return urlify(self.title) 

    @property 
    def created_in_words(self): 
     return time_ago_in_words(self.created) 

    @classmethod 
    def get_paginator(cls, request, page=1): 
     page_url = PageURL_WebOb(request) 
     return Page(Article.all(), page, url=page_url, items_per_page=4) 

View.py

@view_config(route_name='article_action', match_param="action=create", 
      renderer="edit_blog.mako", 
      permission='create') 
def article_create(request): 
    article = Article() 
    form = ArticleCreateForm(request.POST) 
    if request.method == 'POST' and form.validate(): 
     if form.image.data: 
      filename = request.POST['image'].filename 
      input_file = request.POST['image'].file 
      file_path = os.path.join('static/images', filename) 
      with open(file_path, 'wb') as output_file: 
       shutil.copyfileobj(input_file, output_file) 

     form.populate_obj(entry) 
     DBSession.add(entry) 
     return HTTPFound(location=request.route_url('home')) 
    return {'form': form, 'action': request.matchdict.get('action')} 

Файл сохраняется в базе данных, но не хранить в директории изображений.

ответ

1

file является файлоподобным объектом типа python с данными. Думаю, вам следует прочитать и написать то, что вы читаете, output_file.

with input_file as infile, open(file_path, 'wb') as output_file: 
     infile.seek(0) 
     shutil.copyfileobj(infile, output_file) 
+0

Не работает. – ajkumar25

+1

thats what 'shutil.copyfileobj' делает, лучше, чем ваш код: / –

Смежные вопросы