def postimage(self, tid): """ 处理HTML5文件上传 :param tid:教程id """ import base64 from StringIO import StringIO from uliweb.utils.image import thumbnail_image, fix_filename File = get_model('tutorials_albums') if request.method == 'POST': _filename = os.path.join('tutorial/%s' % tid, request.values.get('filename')) fobj = StringIO(base64.b64decode(request.params.get('data'))) filename = functions.save_file(_filename, fobj) #process thumbnail rfilename, thumbnail = thumbnail_image( functions.get_filename(filename, filesystem=True), filename, settings.get_var('TUTORIALS/IMAGE_THUMBNAIL_SIZE')) thumbnail_url = functions.get_href(thumbnail) url = functions.get_href(filename) f = File(filename=filename, tutorial=int(tid)) f.save() return json({ 'success': True, 'data': { 'filename': request.values.get('filename'), 'url': url, 'thumbnail_url': thumbnail_url, 'id': f.id } })
def uploadimage(self, tid): """ 上传图片 :param tid: 论坛id """ import Image from uliweb.utils.image import thumbnail_image, fix_filename from uliweb import json_dumps from uliweb.form import Form, ImageField File = get_model('tutorials_albums') obj = self.model.get_or_notfound(int(tid)) class UploadForm(Form): filename = ImageField() form = UploadForm() flag = form.validate(request.values, request.files) if flag: filename = functions.save_file(os.path.join('tutorials', str(obj.id), form.filename.data.filename), form.filename.data.file) #process thumbnail rfilename, thumbnail = thumbnail_image(functions.get_filename(filename, filesystem=True), filename, settings.get_var('TUTORIALS/IMAGE_THUMBNAIL_SIZE')) thumbnail_url = functions.get_href(thumbnail) url = functions.get_href(filename) f = File(filename=filename, tutorial=int(tid)) f.save() return json({'success':True, 'filename':form.filename.data.filename, 'url':url, 'thumbnail_url':thumbnail_url, 'id':f.id}, content_type="text/html;charset=utf-8") else: #如果校验失败,则再次返回Form,将带有错误信息 return json({'success':False}, content_type="text/html;charset=utf-8")
def _upload_file(self, image=False, show_filename=True): import os import Image if image: from forms import ImageUploadForm as Form else: from forms import FileUploadForm as Form from uliweb.utils.image import thumbnail_image, fix_filename from uliweb import json_dumps File = get_model('forumattachment') forum_id = request.GET.get('forum_id') slug = request.GET.get('slug') form = Form() suffix = date.now().strftime('_%Y_%m_%d') if request.method == 'GET': form.bind({'is_thumbnail': True}) return {'form': form} else: flag = form.validate(request.values, request.files) if flag: f = form.data['filedata'] _f = os.path.basename(f['filename']) #文件格式为forum/<forum_id>/<filename_yyyy_mm_dd> filename = fix_filename('forum/%s/%s' % (forum_id, _f), suffix) if image: filename = functions.save_file(filename, f['file']) if form.data['is_thumbnail']: #process thumbnail rfilename, thumbnail = thumbnail_image( functions.get_filename(filename, filesystem=True), filename, settings.get_var('PARA/FORUM_THUMBNAIL_SIZE')) _file = functions.get_href(thumbnail) else: _file = functions.get_href(filename) name = functions.get_href(filename) else: filename = functions.save_file(filename, f['file']) name = form.data['title'] if not name: name = _f _file = functions.get_href(filename, alt=name) ff = File(slug=slug, file_name=filename, name=name) ff.save() name = json_dumps(name, unicode=True) if show_filename: fargs = '||%s' % name[1:-1] else: fargs = '' return '''<script type="text/javascript"> var url='%s%s'; setTimeout(function(){callback(url);},100); </script> ''' % (_file, fargs) else: return {'form': form}
def _upload_file(self, image=False, show_filename=True): import os import Image if image: from forms import ImageUploadForm as Form else: from forms import FileUploadForm as Form from uliweb.utils.image import thumbnail_image, fix_filename from uliweb import json_dumps File = get_model('forumattachment') forum_id = request.GET.get('forum_id') slug = request.GET.get('slug') form = Form() suffix = date.now().strftime('_%Y_%m_%d') if request.method == 'GET': form.bind({'is_thumbnail':True}) return {'form':form} else: flag = form.validate(request.values, request.files) if flag: f = form.data['filedata'] _f = os.path.basename(f['filename']) #文件格式为<forum_id>/<filename_yyyy_mm_dd> filename = fix_filename('%s/%s' % (forum_id, _f), suffix) if image: filename = functions.save_file(filename, f['file']) if form.data['is_thumbnail']: #process thumbnail rfilename, thumbnail = thumbnail_image(functions.get_filename(filename, filesystem=True), filename, settings.get_var('PARA/FORUM_THUMBNAIL_SIZE')) _file = functions.get_href(thumbnail) else: _file = functions.get_href(filename) name = functions.get_href(filename) else: filename = functions.save_file(filename, f['file']) name = form.data['title'] if not name: name = _f _file = functions.get_href(filename, alt=name) ff = File(slug=slug, file_name=filename, name=name) ff.save() name = json_dumps(name, unicode=True) if show_filename: fargs = '||%s' % name[1:-1] else: fargs = '' return '''<script type="text/javascript"> var url='%s%s'; setTimeout(function(){callback(url);},100); </script> ''' % (_file, fargs) else: return {'form':form}
def mp3upload(self, forum_id, slug): """ mp3上传显示及上传处理 """ if request.method == 'POST': _filename = 'forum/%s/%s.mp3' % (forum_id, slug) filename = functions.save_file(_filename, request.stream) Mp3 = get_model('forummp3') obj = Mp3(filename=functions.get_href(filename)) obj.save() return json({'success':True, "filename":functions.get_href(filename)}) else: return {}
def get_image(self): from uliweb import functions if self.image: return functions.get_href(self.image) else: return functions.url_for_static('tutorials/default_book.png')
def edit_image(self): from forms import UploadImageForm from uliweb.utils.generic import EditView import os import Image def pre_save(obj, data): if 'image' in data and data['image']: data['image'].filename = _get_portrait_image_filename( request.user.id) image = _get_portrait_image_filename(request.user.id) f = functions.get_filename(image) if os.path.exists(f): url = functions.get_href(image) img = Image.open(f) template_data = {'image_url': url, 'size': img.size} else: url = None template_data = {'image_url': url, 'size': (0, 0)} view = EditView('user', condition=request.user.id, ok_url=url_for(UserView.edit_image), pre_save=pre_save, fields=['image'], template_data=template_data, file_convert=False) return view.run()
def view(self, id): from uliweb.utils.generic import DetailView from uliweb import orm from uliweb.contrib.upload import get_filename, get_url import os User = orm.get_model('user') def boolean_convert(b, obj): if b: return '<div class="ui-icon ui-icon-check"></div>' else: return '<div class="ui-icon ui-icon-closethick"></div>' user = User.get(int(id)) if not user: error(_('User is not exists!')) image = functions.get_filename(_get_portrait_image_thumbnail(user.id)) if os.path.exists(image): image_url = functions.get_href( _get_portrait_image_thumbnail(user.id)) else: image_url = user.get_image_url() can_modify = user.id == request.user.id template_data = {'image_url': image_url, 'can_modify': can_modify} view = DetailView('user', obj=user, template_data=template_data, table_class_attr='table table-bordered') view.types_convert_map = {orm.BooleanProperty: boolean_convert} return view.run()
def get_image(self): from uliweb import functions if self.logo: return functions.get_href(self.logo) else: return functions.url_for_static('classes/default_class.png')
def _clear_files(self, slug, text): import re import itertools from uliweb.utils.image import fix_filename File = get_model('forumattachment') r_links = re.compile( r'<a.*?href=\"([^"\?]+)(?:\"|\?)|<img.*?src=\"([^"]+)\"|<embed.*?src=\"([^"]+)\"', re.DOTALL) files = filter(None, itertools.chain(*re.findall(r_links, text))) for row in File.filter(File.c.slug == slug): _f = functions.get_filename(row.file_name) url = functions.get_href(row.file_name) if url in files: row.enabled = True row.save() else: if os.path.exists(_f): os.unlink(_f) thumbnail = fix_filename(_f, '.thumbnail') if os.path.exists(thumbnail): os.unlink(thumbnail) File.filter(File.c.slug == slug).filter( File.c.enabled == False).remove()
def view(self, id): from uliweb.utils.generic import DetailView from uliweb import orm from uliweb.contrib.upload import get_filename, get_url import os User = orm.get_model('user') def boolean_convert(b, obj): if b: return '<div class="ui-icon ui-icon-check"></div>' else: return '<div class="ui-icon ui-icon-closethick"></div>' user = User.get(int(id)) if not user: error(_('User is not exists!')) image = functions.get_filename(_get_portrait_image_thumbnail(user.id)) if os.path.exists(image): image_url = functions.get_href(_get_portrait_image_thumbnail(user.id)) else: image_url = user.get_image_url() can_modify = user.id == request.user.id template_data = {'image_url':image_url, 'can_modify':can_modify} view = DetailView('user', obj=user, template_data=template_data, table_class_attr='table table-bordered') view.types_convert_map = {orm.BooleanProperty:boolean_convert} return view.run()
def paste_image(self): """ 图片上传处理 """ import base64 from StringIO import StringIO from uliweb.utils.common import log File = get_model('forumattachment') forum_id = request.GET.get('forum_id') slug = request.GET.get('slug') filename='forum/%s/%s.png' % (forum_id, slug) data = request.POST.get('urls') prefix = 'data:image/png;base64,' if data.startswith(prefix): fobj = StringIO(base64.b64decode(data[len(prefix):])) nname=functions.save_file(filename, fobj) url_name=functions.get_href(nname) ff = File(slug=slug, file_name=nname, name=nname) ff.save() return url_name else: return data
def _clear_files(self, slug, text): import re import itertools from uliweb.utils.image import fix_filename File = get_model("forumattachment") r_links = re.compile( r'<a.*?href=\"([^"\?]+)(?:\"|\?)|<img.*?src=\"([^"]+)\"|<embed.*?src=\"([^"]+)\"', re.DOTALL ) files = filter(None, itertools.chain(*re.findall(r_links, text))) for row in File.filter(File.c.slug == slug): _f = functions.get_filename(row.file_name) url = functions.get_href(row.file_name) if url in files: row.enabled = True row.save() else: if os.path.exists(_f): os.unlink(_f) thumbnail = fix_filename(_f, ".thumbnail") if os.path.exists(thumbnail): os.unlink(thumbnail) File.filter(File.c.slug == slug).filter(File.c.enabled == False).remove()
def get_image_url(self): from uliweb.contrib.upload import get_url from uliweb.contrib.staticfiles import url_for_static if self.image: return functions.get_href(self.image) else: return functions.url_for_static('images/user%dx%d.jpg' % (50, 50))
def getimages(self, tid): """ 返回图片 :param tid: tutorial id """ from uliweb.utils.image import thumbnail_image, fix_filename File = get_model('tutorials_albums') data = {'data': [], 'success': True} for row in File.filter(File.c.tutorial == int(tid)): d = {} thumbnail_filename = fix_filename(row.filename, '.thumbnail') d['thumbnail_url'] = functions.get_href(thumbnail_filename) d['url'] = functions.get_href(row.filename) d['id'] = row.id data['data'].append(d) return json(data)
def getimages(self, tid): """ 返回图片 :param tid: tutorial id """ from uliweb.utils.image import thumbnail_image, fix_filename File = get_model('tutorials_albums') data = {'data':[], 'success':True} for row in File.filter(File.c.tutorial==int(tid)): d = {} thumbnail_filename = fix_filename(row.filename, '.thumbnail') d['thumbnail_url'] = functions.get_href(thumbnail_filename) d['url'] = functions.get_href(row.filename) d['id'] = row.id data['data'].append(d) return json(data)
def uploadimage(self, tid): """ 上传图片 :param tid: 论坛id """ import Image from uliweb.utils.image import thumbnail_image, fix_filename from uliweb import json_dumps from uliweb.form import Form, ImageField File = get_model('tutorials_albums') obj = self.model.get_or_notfound(int(tid)) class UploadForm(Form): filename = ImageField() form = UploadForm() flag = form.validate(request.values, request.files) if flag: filename = functions.save_file( os.path.join('tutorials', str(obj.id), form.filename.data.filename), form.filename.data.file) #process thumbnail rfilename, thumbnail = thumbnail_image( functions.get_filename(filename, filesystem=True), filename, settings.get_var('TUTORIALS/IMAGE_THUMBNAIL_SIZE')) thumbnail_url = functions.get_href(thumbnail) url = functions.get_href(filename) f = File(filename=filename, tutorial=int(tid)) f.save() return json( { 'success': True, 'filename': form.filename.data.filename, 'url': url, 'thumbnail_url': thumbnail_url, 'id': f.id }, content_type="text/html;charset=utf-8") else: #如果校验失败,则再次返回Form,将带有错误信息 return json({'success': False}, content_type="text/html;charset=utf-8")
def get_user_image(user, size=50): from uliweb.contrib.staticfiles import url_for_static from uliweb import functions import os if user: image = functions.get_filename(_get_portrait_image_thumbnail(user.id, size)) if os.path.exists(image): image_url = functions.get_href(_get_portrait_image_thumbnail(user.id, size)) return image_url return functions.url_for_static('images/user%dx%d.jpg' % (size, size))
def uploadfile(): from uliweb.form import Form, FileField from uliweb.utils.image import test_image, thumbnail_image fileserving = AttachmentsFileServing() Attachment = functions.get_model('generic_attachment') class UploadForm(Form): fileupload = FileField() def form_validate(self, data): error = {} return error form = UploadForm() table = request.GET.get('table') id = request.GET.get('id') slug = request.GET.get('slug') if form.validate(request.values, request.files): dir = settings.Generic_Attachment_Save_Dirs.get(table) if not dir: raise Exception("Saving directory of table %s is not defined in Generic_Attachment_Save_Dirs" % table) if id: path = os.path.join(dir, id) else: path = dir filename = fileserving.save_file(os.path.join(path, form.fileupload.data.filename), form.fileupload.data.file) is_image = test_image(filename) if is_image and settings.get_var('Generic_Attachment_FileServing/THUMBNAIL_PROCESS'): thumbnail_path, thumbnail = thumbnail_image(functions.get_filename(filename, filesystem=True), filename, settings.get_var('Generic_Attachment_FileServing/IMAGE_THUMBNAIL_SIZE')) thumbnail_url = functions.get_href(thumbnail) else: thumbnail = '' thumbnail_url = '' f = Attachment(filepath=filename, filename=form.fileupload.data.filename, submitter=request.user.id, is_image=is_image, thumbnail_path=thumbnail) if slug: f.slug = slug else: f.content_object = (table, id) f.save() url = fileserving.get_url(filename, title=f.filename, query_para={'alt':f.filename}, _class='filedown') href = fileserving.get_href(filename, alt=f.filename) return json({'success':True, 'filename':f.filename, 'url':url, 'href':href, 'id':f.id, 'submitter':unicode(request.user), 'is_image':is_image, 'thumbnail_url':thumbnail_url, 'created_date':str(f.created_date)}, content_type="text/html;charset=utf-8") else: #如果校验失败,则再次返回Form,将带有错误信息 return json({'success':False}, content_type="text/html;charset=utf-8")
def postimage(self, tid): """ 处理HTML5文件上传 :param tid:教程id """ import base64 from StringIO import StringIO from uliweb.utils.image import thumbnail_image, fix_filename File = get_model('tutorials_albums') if request.method == 'POST': _filename = os.path.join('tutorial/%s' % tid, request.values.get('filename')) fobj = StringIO(base64.b64decode(request.params.get('data'))) filename = functions.save_file(_filename, fobj) #process thumbnail rfilename, thumbnail = thumbnail_image(functions.get_filename(filename, filesystem=True), filename, settings.get_var('TUTORIALS/IMAGE_THUMBNAIL_SIZE')) thumbnail_url = functions.get_href(thumbnail) url = functions.get_href(filename) f = File(filename=filename, tutorial=int(tid)) f.save() return json({'success':True, 'data':{'filename':request.values.get('filename'), 'url':url, 'thumbnail_url':thumbnail_url, 'id':f.id}})
def get_user_image(user, size=50): from uliweb.contrib.staticfiles import url_for_static from uliweb import functions import os if user: image = functions.get_filename( _get_portrait_image_thumbnail(user.id, size)) if os.path.exists(image): image_url = functions.get_href( _get_portrait_image_thumbnail(user.id, size)) return image_url return functions.url_for_static('images/user%dx%d.jpg' % (size, size))
def fileupload(): from uliweb.form import Form, FileField class UploadForm(Form): filename = FileField() form = UploadForm() flag = form.validate(request.values, request.files) if flag: filename = functions.save_file(form.filename.data.filename, form.filename.data.file) url = functions.get_href(filename, alt=form.filename.data.filename) return json({'success':True, 'filename':filename, 'alt':form.filename.data.filename, 'url':url}) else: print form.errors #如果校验失败,则再次返回Form,将带有错误信息 return json({'success':False, 'errors':form.errors})
def postimage(): """ 处理HTML5文件上传 """ import base64 from StringIO import StringIO from uliweb.utils.image import thumbnail_image, fix_filename from uliweb.form import Form, FileField fileserving = AttachmentsFileServing() Attachment = functions.get_model('generic_attachment') table = request.values.get('table') id = request.values.get('id') slug = request.values.get('slug') if request.method == 'POST': dir = settings.Generic_Attachment_Save_Dirs.get(table) if not dir: raise Exception("Saving directory of table %s is not defined in Generic_Attachment_Save_Dirs" % table) if id: path = os.path.join(dir, id, request.values.get('filename')) else: path = os.path.join(dir, request.values.get('filename')) fobj = StringIO(base64.b64decode(request.params.get('data'))) filename = functions.save_file(path, fobj) if settings.get_var('Generic_Attachment_FileServing/THUMBNAIL_PROCESS'): thumbnail_path, thumbnail = thumbnail_image(functions.get_filename(filename, filesystem=True), filename, settings.get_var('Generic_Attachment_FileServing/IMAGE_THUMBNAIL_SIZE')) thumbnail_url = functions.get_href(thumbnail) else: thumbnail = '' thumbnail_url = '' fname = os.path.splitext(os.path.basename(filename))[0].split(',')[-1][:8] f = Attachment(filepath=filename, filename=fname, is_image=True, submitter=request.user.id, thumbnail_path=thumbnail) if slug: f.slug = slug else: f.content_object = (table, id) f.save() url = fileserving.get_url(filename, title=f.filename, alt=f.filename, _class='filedown') href = fileserving.get_href(filename, title=f.filename, query_para={'alt':f.filename}) return json({'success':True, 'filename':f.filename, 'submitter':unicode(request.user), 'url':url, 'href':href, 'is_image':f.is_image, 'id':f.id, 'created_date':str(f.created_date), 'thumbnail_url':thumbnail_url, })
def draw(self, forum_id, slug): import base64 from StringIO import StringIO File = get_model('forumattachment') filename = 'forum/%s/%s.png' % (forum_id, slug) if request.method == 'POST': fobj = StringIO(base64.b64decode(request.params.get('text1'))) nname = functions.save_file(filename, fobj) url_name = functions.get_href(nname) ff = File(slug=slug, file_name=nname, name=nname) ff.save() return {'url_name': url_name} if request.method == 'GET': return {'forum_id': forum_id, 'slug': slug}
def draw(self, forum_id, slug): import base64 from StringIO import StringIO File = get_model("forumattachment") filename = "forum/%s/%s.png" % (forum_id, slug) if request.method == "POST": fobj = StringIO(base64.b64decode(request.params.get("text1"))) nname = functions.save_file(filename, fobj) url_name = functions.get_href(nname) ff = File(slug=slug, file_name=nname, name=nname) ff.save() return {"url_name": url_name} if request.method == "GET": return {"forum_id": forum_id, "slug": slug}
def draw(self, forum_id, slug): import base64 from StringIO import StringIO File = get_model('forumattachment') filename='%s/%s.png' % (forum_id, slug) if request.method == 'POST': fobj = StringIO(base64.b64decode(request.params.get('text1'))) nname=functions.save_file(filename, fobj) url_name=functions.get_href(nname) ff = File(slug=slug, file_name=nname, name=nname) ff.save() return {'url_name':url_name} if request.method == 'GET': return {'forum_id':forum_id,'slug':slug}
def view(self): user_id = request.values.get("id", 0).strip() User = functions.get_model("user") if user_id: user = User.get(int(user_id)) ldapuser = functions.ldap_get_user(username=user.username) image = functions.get_filename( _get_portrait_image_thumbnail(user.id)) if os.path.exists(image): image_url = functions.get_href( _get_portrait_image_thumbnail(user.id)) else: image_url = user.get_image_url() can_modify = user.id == request.user.id else: error(_('error: para userid does not exist!')) return { "can_modify": can_modify, "image_url": image_url, "user": user.to_dict(), "ldapuser": ldapuser }
def edit_image(self): from forms import UploadImageForm from uliweb.utils.generic import EditView import os from PIL import Image def pre_save(obj, data): if 'image' in data and data['image']: data['image'].filename = _get_portrait_image_filename(request.user.id) image = _get_portrait_image_filename(request.user.id) f = functions.get_filename(image) if os.path.exists(f): url = functions.get_href(image) img = Image.open(f) template_data = {'image_url':url, 'size':img.size} else: url = None template_data = {'image_url':url, 'size':(0, 0)} view = EditView('user', condition=request.user.id, ok_url=url_for(UserView.edit_image), pre_save=pre_save, fields=['image'], template_data=template_data, file_convert=False) return view.run()
def edit_image(self): from .forms import UploadImageForm import os from PIL import Image file_image = request.files.get('image') if file_image: filename = _get_portrait_image_filename(request.user.id) functions.save_file(filename, file_image, replace=True, convert=False) image = _get_portrait_image_filename(request.user.id) f = functions.get_filename(image) if os.path.exists(f): url = functions.get_href(image) img = Image.open(f) template_data = {'image_url': url, 'size': img.size} else: url = None template_data = {'image_url': url, 'size': (0, 0)} return template_data
def get_image_url(self): if self.image: return functions.get_href(self.image) else: return functions.url_for_static('images/user%dx%d.jpg' % (50, 50))
def _upload_file(self, image=False, show_filename=True): import os import Image if image: from forms import ImageUploadForm as Form else: from forms import FileUploadForm as Form from uliweb.utils.image import thumbnail_image, fix_filename from uliweb import json_dumps File = get_model("forumattachment") forum_id = request.GET.get("forum_id") slug = request.GET.get("slug") form = Form() suffix = date.now().strftime("_%Y_%m_%d") if request.method == "GET": form.bind({"is_thumbnail": True}) return {"form": form} else: flag = form.validate(request.values, request.files) if flag: f = form.data["filedata"] _f = os.path.basename(f["filename"]) # 文件格式为forum/<forum_id>/<filename_yyyy_mm_dd> filename = fix_filename("forum/%s/%s" % (forum_id, _f), suffix) if image: filename = functions.save_file(filename, f["file"]) if form.data["is_thumbnail"]: # process thumbnail rfilename, thumbnail = thumbnail_image( functions.get_filename(filename, filesystem=True), filename, settings.get_var("PARA/FORUM_THUMBNAIL_SIZE"), ) _file = functions.get_href(thumbnail) else: _file = functions.get_href(filename) name = functions.get_href(filename) else: filename = functions.save_file(filename, f["file"]) name = form.data["title"] if not name: name = _f _file = functions.get_href(filename, alt=name) ff = File(slug=slug, file_name=filename, name=name) ff.save() name = json_dumps(name, unicode=True) if show_filename: fargs = "||%s" % name[1:-1] else: fargs = "" return """<script type="text/javascript"> var url='%s%s'; setTimeout(function(){callback(url);},100); </script> """ % ( _file, fargs, ) else: return {"form": form}