我正在使用基本的 WTForms FileField 到目前为止我能够上传文件,但它没有存储在目录中,但是它存储在 POSTGRESQL < / strong>数据库为<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')}
文件存储在数据库中,但不存储在images目录中。
答案 0 :(得分: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)