Hi all !

It was a lot of questions about the upload with webpy. I wrote a document 
store application in webpy based on jquery fileupload. This handles upload 
! All files stored in Mongodb Gridfs with versioning.  Live demo available 
at http://docman.pageos.hu (Sorry, only hungarian) After registration, or 
google account login the demo project connected to user automatically. Yue 
can test it. The source of upload handler int attachement.
2014. február 19., szerda 22:07:22 UTC+1 időpontban Jessica Le a következőt 
írta:
>
> Hi all,
>
>
> What I want to be able to do is have a file upload button that lets the 
> user upload an .xls file and either save it in memory or to the server, so 
> I can take the file and parse it for later use. I have tried using the file 
> upload recipe on the website (http://webpy.org/cookbook/fileupload), but 
> I get an error when I try to upload an Excel file, but it works fine for a 
> .txt document. Some have suggested using an Excel library (xlrd) to do so, 
> but that library would only work AFTER I upload the file. I need to know 
> how to upload the Excel file without it throwing an error. The error that I 
> receive when I upload the Excel file is UnicodeDecodeError. Is there 
> another way to upload an Excel file other than using webpy's file upload 
> recipe? I'm starting to think I should switch frameworks, since there isn't 
> much documentation for webpy...
>
>
> Python CODE: 
>
> class index:
>     def GET(self):
>     web.header("Content-Type","text/html;")
>     return render.index(form)
>     def POST(self):
>         x = web.input(calendar_file={})
>
> calendar_contents = x['calendar_file'].value
> return render.results(calendar_contents)
>
> ------
> HTML CODE: 
>
> $def with (form) 
> <div class="well well-lg">
> <h4> GENERATE ON-CALL SCHEDULE </h4>
> <form role="form" method="POST"enctype="multipart/form-data" action="">
> <div class="form-group">
> <label form="inputFile">Upload File</label>
>     <input type="file"  name="calendar_file" id="file"/>
> </div>
>   <button type="submit" class="btn btn-default" 
> value="upload">Submit</button>
> </form>
> </div>
>

-- 
You received this message because you are subscribed to the Google Groups 
"web.py" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/webpy.
For more options, visit https://groups.google.com/groups/opt_out.
# coding: utf-8
import web
from web import form
import time
import pymongo
from pymongo import Connection
from bson import ObjectId
import json
import config
from myutils import *
import projects
import users
import gridfs
import gridfile
import logs
from logs import wlog

import os, urllib
from PIL import Image
import pgmagick
import subprocess    

 #a mongodb projekteket tartalmaz? collection neve
locks=config.mdb.locks
locks.ensure_index('filename',unique=True)   

def islocked(filename,thumbnail=False):
   mname=u'uploads.islocked'
   uzenet=u'elindult! filename='+to_unicode_or_bust(filename)
   wlog(mname,0,uzenet,4)
   #vissza : locked true=lockid, locked false=False           
   re=locks.find_one({'filename':filename,'thumbnail':thumbnail})    
   if not re is None :
     return re
   uzenet=u'lock in db not found'
   wlog(mname,0,uzenet,4)  
   return False

def lockfile(filename=None,size=0,thumbnail=False,uid=None):
    mname=u'uploads.lockfile'
    uzenet=u'elindult! filename='+to_unicode_or_bust(filename)
    wlog(mname,0,uzenet,4) 
    if  filename is None:
      return None
    vissza=islocked(filename,thumbnail)             
    if vissza is False:
      # m?g nincs ilyen lock
      if uid is None:
        uid=web.ctx.session.uid
      data={'filename':filename,'size':size,'thumbnail':thumbnail,'createtime':time.time(),'qtime':time.time(),'uid':uid, 'db':1}
      lockid=locks.insert(data,manipulate=True,safe=True)
      if lockid is not None:
         return  lockid
      else:
         return None   
    else:
       #aktualiz?lom a qtime-t, hogy a megszakadt felt?lt?st azonos?tani lehessen
       db=int(vissza['db'])+1      
       locks.update({'_id': vissza['_id']},{"$set":{'qtime':time.time(), 'db':db}}, safe=True)
       return vissza['_id']
   
     
def getLockInfobyID(id):
   if not type(id).__name__=='ObjectId':
     id=ObjectId(id)        
   re=locks.find_one({'_id':id})    
   if not re is None :
     return re
   else:
     return None
     
def removelock(id):           
   if not type(id).__name__=='ObjectId':
     id=ObjectId(id)
   try:          
     locks.remove({'_id':id}) 
     return True
   except:
     return False
                        
# This part should go inside your model
class UploadHandler:

  def __init__(self, options=None):
    self.__options = {
          'script_url' : '/upload',
          'cur_dir': None,
          'dir_id': None,
          'upload_dir': '', # Maybe this
          'upload_url': '/projectfiles', # .. and this should removed?
          'param_name': 'files',
          'max_file_size': None,
          'min_file_size': 1,
          'accept_file_types': 'ALL',
          'max_number_of_files': None,
          'discard_aborted_uploads': True,
          'image_versions': {
                  'thumbnail': {
                        'upload_dir': '',
                        'upload_uri': '/thumbnails/',
                        'max_width': 80,
                        'max_height': 80
                        }
                  }
          }
    if options:
      self.__options = options

  def __get_file_object(self, actfile):
    mname=u'uploads.__get_file_object'
    uzenet=u'elindult! file_name='+to_unicode_or_bust(actfile.name)
    wlog(mname,0,uzenet,4)
    myactfile=gridfile.gridfile(prj_id=web.ctx.session.selected_prj,filename=actfile.filename,showdeleted=web.ctx.session.showdeleted)
          
    myfile = {}
    myfile['name'] = to_unicode_or_bust(actfile.name)
    myfile['id'] = str(actfile._id)
    myfile['dir_id']=self.__options['dir_id']
    myfile['size'] = actfile.length
    myfile['url'] = to_unicode_or_bust(self.__options['upload_url'] + actfile.filename)        
    myfile['locked']= actfile.locked['locked']
    myfile['lockedby']= actfile.locked['uid']
    myfile['deleted']= actfile.deleted['deleted']
    myfile['delete_url'] = to_unicode_or_bust(self.__options['script_url']) +u'?file='+to_unicode_or_bust(myfile['name'])+u'&dir_id='+str(self.__options['dir_id'])+u'&fileid='+str(actfile._id)    
    myfile['versions']=[]
    vfile={}
    db=myactfile.countversion()
    uzenet=u'version db='+str(db)
    wlog(mname,0,uzenet,4)    
    if db > 1:
      # vannak verziok, azokat is ?ssze kell szedni
      versions=myactfile.getversions()
      for actv in versions:
        vfile['name'] = to_unicode_or_bust(actv.name)
        vfile['id'] = str(actv._id)
        vfile['dir_id']=self.__options['dir_id']
        vfile['size'] = actv.length
        vfile['url'] = to_unicode_or_bust(self.__options['upload_url'] + actv.filename)        
        vfile['locked']= actv.locked['locked']
        vfile['lockedby']= actv.locked['uid']
        vfile['deleted']= actv.deleted['deleted']
        vfile['delete_url'] = to_unicode_or_bust(self.__options['script_url']) +u'?file='+to_unicode_or_bust(vfile['name'])+u'&dir_id='+str(self.__options['dir_id'])+u'&fileid='+str(actv._id)    
        myfile['versions'].append(vfile)
        vfile={}    
   
    for imgversion,options in self.__options['image_versions'].items():
      #uzenet=u'version ='+unicode(version)+ ' options='+ unicode(options)
      #wlog(mname,0,uzenet,4)
      if self.__create_scaled_image(actfile, options):
         name_ext = actfile.name.split(".")         
         name =name_ext[0]
         myfile[imgversion+'_url']= options['upload_uri']+ name+'.jpg'
    
    
      #uzenet=u'elindult! myfile='+unicode(myfile)
      #wlog(mname,0,uzenet,4)
    return myfile

   # return None

  def __get_file_objects(self):
    mname=u'uploads.__get_file_objects'
    #uzenet=u'elindult! dir='+self.__options['upload_dir']
    #wlog(mname,0,uzenet,4)
    files = []    
    dirfiles=self.__options['upload_dir'].getfiles()
    if dirfiles:
      for actfile in dirfiles:
        rv=self.__get_file_object(actfile)
        if rv:
           files.append(rv)
         
    return files

  def __create_scaled_image(self, actfile, options):
      mname=u'uploads.__create_scaled_image'
      file_name=to_unicode_or_bust(actfile.name)      
      uzenet=u'elindult! file_name='+to_unicode_or_bust(file_name)
      wlog(mname,0,uzenet,4)
      #ezek vannak az optionsban
      
      size = options['max_width'], options['max_height']
      gfs_thumbnail=options['upload_dir']
      
      name_ext = file_name.split(".")
      ext = name_ext[-1].lower()
      name =name_ext[0]
      cType = config.mimetypes        
      if cType.has_key(ext):
         # megn?zem a mime config alapj?n   
         curmime=cType[ext]
         uzenet=u'tipus ='+to_unicode_or_bust(curmime)
         wlog(mname,0,uzenet,4)
         if 'image'in curmime:
           mode='image'
         elif 'application/pdf' == curmime: 
           mode='pdf'
         elif 'application/msword' == curmime:
           mode='word'
         elif 'application/rtf'== curmime:
           mode='word'  
         else:
          #ez nem is image f?jl
           return False
         
         path=os.path.dirname(actfile.filename)+u'/'             
         outfile =to_unicode_or_bust(path+name+'.jpg').encode("utf-8")
         uzenet=u'ez jo tipus mode='+ to_unicode_or_bust(mode)+' orig name='+to_unicode_or_bust(actfile.filename) + ' outfile='+to_unicode_or_bust(outfile)
         wlog(mname,0,uzenet,4)
         #lockname=to_unicode_or_bust(config.tmp_dir+file_name).encode("utf-8")
         lockname=outfile
                 
         if gfs_thumbnail.exists({"filename": outfile}):         
            return True
         else:            
            uuid=islocked(lockname,thumbnail=True)
            if not uuid is False:
               return True
            # ezt kirakom ide, hogy min?ll hamarabb l?trej?jj?n a file, k?l?nben t?l lass? a folyamat ?s t?bbsz?r is l?trej?het
            uuid=lockfile(lockname,thumbnail=True)
            #lock = open(lockname, 'w')
            f = gfs_thumbnail.new_file(filename=outfile,parentid=actfile._id,contentType='image/jpeg')                 
         #try:
         if mode=='image':
             myfile=self.__options['upload_dir'].gfs.get_last_version(actfile.filename)
             im = Image.open(myfile)
             im.thumbnail(size, Image.ANTIALIAS)             
             im.save(f, "JPEG")
             f.close()
             #lock.close()
             #os.remove(lockname)
             removelock(uuid)
             return True
         if mode=='pdf':
             myfile=self.__options['upload_dir'].gfs.get_last_version(actfile.filename)
             blob = pgmagick.Blob(myfile.read())
             imp = pgmagick.Image(blob, pgmagick.Geometry(options['max_width'], options['max_height']))             
             tjpgfname=str(config.tmp_dir+str(uuid)+'.jpg') # ez egy tmp jpeg k?p a pdf-b?l
             imp.write(tjpgfname)
             im = Image.open(tjpgfname)
             im.thumbnail(size, Image.ANTIALIAS)
             #f = gfs_thumbnail.new_file(filename=outfile,parentid=actfile._id,contentType='image/jpeg')
             im.save(f, "JPEG")
             f.close()
             os.remove(tjpgfname) # a tmp jpeg k?p t?rl?se
             removelock(uuid)            
             return True
         if mode=='word': 
             myfile=self.__options['upload_dir'].gfs.get_last_version(actfile.filename)             
             tfname=str(config.tmp_dir+str(uuid)+'.'+ext) # ez egy tmp f?j, az aktu?lis f?jl kiterjeszt?s?vel
             tpdffname=str(config.tmp_dir+str(uuid)+'.pdf') # ez egy tmp f?j, az pdf kiterjeszt?s?vel
             tjpgfname=str(config.tmp_dir+str(uuid)+'.jpg') # ez egy tmp jpeg k?p a pdf-b?l
             tf = open(tfname, 'w')
             tf.write(myfile.read())
             tf.close() # k?sz a f?jl, ezt kell ?talak?tani pdf-? az abiworddel
             #if call("timelimit -t 30 -- abiword --to=pdf '%s' -o '%s'" % (self.in_file, self.tmp_pdf_path), shell=True) != 0:
             cmd="timelimit -t 10 -- /usr/bin/abiword --to=pdf "+ tfname
             if subprocess.call(cmd,shell=True) != 0:
                 # e t?l nagy f?jl
                 im = Image.open(config.imgdir+'/defaultdoc.png')
                 im.save(f, "PNG")
                 f.close()
                 os.remove(tfname)
                 removelock(uuid)
                 return True            
             #innent?l, mint a pdf
             pdf = open(tpdffname, 'r')
             blob = pgmagick.Blob(pdf.read())
             imp = pgmagick.Image(blob, pgmagick.Geometry(options['max_width'], options['max_height']))                         
             imp.write(tjpgfname)
             im = Image.open(tjpgfname)
             im.thumbnail(size, Image.ANTIALIAS)
             #f = gfs_thumbnail.new_file(filename=outfile,parentid=actfile._id,contentType='image/jpeg')
             im.save(f, "JPEG")
             f.close()
             os.remove(tfname)
             os.remove(tpdffname)
             os.remove(tjpgfname)
             removelock(uuid)
             return True
         #except:
          #  os.remove(tfname)
          #  os.remove(tpdffname)
          #  os.remove(tjpgfname)
          #  os.remove(lockname)        
         #  return False                
                           
      else:
        return False
        
  def __has_error(self, uploaded_file, ufile, error):
    if error:
      return error
    #if ufile.name.split['.'][-1:][0] not in \
    #    self.__options['accepted_file_types'] and \
    #    self.__options['accepted_file_types'] != "ALL":
    #  return 'acceptFileTypes'
    if self.__options['max_file_size'] and \
      (file_size > self.__options['max_file_size'] or \
        ufile.size > self.__options['max_file_size']):
      return 'maxFileSize'

    if self.__options['min_file_size'] and \
      file_size > self.__options['min_file_size']:
      return 'minFileSize'

    if self.__options['max_number_of_files'] and \
      int(self.__options['max_number_of_files']) <= \
        len(self.__get_file_objects):
      return 'maxNumberOfFiles'
    return None   
      
  def __handle_file_upload(self, uploaded_file, name, size, type, error, blob=False):
    mname=u'uploads.UploadHandler.__handle_file_upload'              
    uzenet=u'elindult! name='+ to_unicode_or_bust(name) +  ' type=' + to_unicode_or_bust(type) + ' size='+ unicode(size) + u' blob='+str(blob)
    wlog(mname,0,uzenet,4)
    ufiles=[]
    ufile ={}          
    ufile['versions']=[]   
    ufile['name'] = to_unicode_or_bust(name)
    ufile['dir_id']=str(self.__options['dir_id'])
    ufile['type'] = type
    #error = self.__has_error(uploaded_file, ufile, error)
    #if error:
    #  error ='File error'
    #else:
    error = None

    if not error and ufile['name']:
      fullname = os.path.join(to_unicode_or_bust(self.__options['cur_dir']).encode("utf-8"),to_unicode_or_bust( ufile['name']).encode("utf-8"))  
      
      #append_file = not self.__options['discard_aborted_uploads'] and os.path.isfile(file_path) and ufile['size'] > os.path.getsize(file_path)               
      new_file_id=None
      if uploaded_file:
      # multipart/formdata uploads (POST method uploads)            
          if blob:
            # t?bb r?szletben j?n a felt?lt?s
            lockid=lockfile(fullname,thumbnail=False)
            if not lockid is None:             
              tmpfilename=to_unicode_or_bust(config.tmp_dir+str(lockid)).encode("utf-8")
              mylockinfo=getLockInfobyID(lockid)            
              if time.time() - mylockinfo['qtime'] > 120:
                 # 2 perc sz?net volt val?sz?n?leg megszakadt
                 uzenet=u'eltelt id? t?l nagy, delta='+ str(time.time()-mylockinfo['qtime'])
                 wlog(mname,0,uzenet,4)                 
                 removelock(lockid)
                 try:
                   os.remove(tmpfilename)
                 except:
                   uzenet=u'tmpfilename ='+unicode(tmpfilename) + u' t?rl?s hiba!'
                   wlog(mname,0,uzenet,4) 
                 # ?J LOCKF?JLT HOZOK L?TRE
                 lockid=lockfile(fullname,thumbnail=False)
                 tmpfilename=to_unicode_or_bust(config.tmp_dir+str(lockid)).encode("utf-8")                                      
                            
              try:
                 tmp_file = open(tmpfilename, 'ab')
                 data=uploaded_file.read()
                 uzenet=u'beolvasott chunk m?rete='+str(len(data))+ u' tmpfilename='+tmpfilename
                 wlog(mname,0,uzenet,4)
                 tmp_file.write(data)
                 tmp_file.seek(0,2)                
                 actsize=tmp_file.tell()
                 uzenet=u'actsize='+ str(actsize) +  ' size=' + str(size)
                 wlog(mname,0,uzenet,4)
                 if  actsize<size:
                    tmp_file.close()                
                    return False                            
                 else:
                   # el?rte a v?gleges m?ret?t, ki?rhatom az adatb?zisba !!
                     mycreated={'uid':web.ctx.session.uid,'time':time.time()}
                     mylocked={'locked':False,'uid':None,'time':None}
                     mydeleted={'deleted':False,'uid':None,'time':None}
                     tmp_file.close()
                     tmp_file = open(tmpfilename, 'rb')
                     new_file_id=self.__options['upload_dir'].gfs.put(tmp_file.read(), filename=fullname, name=ufile['name'], dir_id=self.__options['dir_id'], contentType=ufile['type'], created=mycreated, locked=mylocked, deleted=mydeleted )
                     tmp_file.close()
                     removelock(lockid)
                     os.remove(tmpfilename)
              except:
                 uzenet=u'uploaded_file.read(), tmp_file.write(data) exeption'
                 wlog(mname,0,uzenet,4)
                 tmp_file.close()                
                 return False              
            else:
              ufile['error'] = error
          else:
             mycreated={'uid':web.ctx.session.uid,'time':time.time()}
             mylocked={'locked':False,'uid':None,'time':None}
             mydeleted={'deleted':False,'uid':None,'time':None}
             new_file_id=self.__options['upload_dir'].gfs.put(uploaded_file.read(), filename=fullname, name=ufile['name'], dir_id=self.__options['dir_id'], contentType=ufile['type'], created=mycreated, locked=mylocked, deleted=mydeleted )

          if not new_file_id is None:
            ufile['id'] = str(new_file_id)
            ufile['locked']= False
            ufile['lockedby']= None
            ufile['deleted']=False
            file_size = self.__options['upload_dir'].gfs.get(new_file_id).length
            ufile['size'] = file_size
            # if file_size == ufile['size'] :
            ufile['url'] = self.__options['upload_url'] + to_unicode_or_bust( ufile['name'])
              #.replace(" ", "%20")
            self.__options['discard_aborted_uploads']=False
              #for version,options in self.__options['image_versions'].items():
                #uzenet=u'version ='+unicode(version)+ ' options='+ unicode(options)
                #wlog(mname,0,uzenet,4)
                #if self.__create_scaled_image(ufile['name'], options):
                #   ufile[version+'_url']= options['upload_uri']+ to_unicode_or_bust( ufile['name'])                     
                      
            #elif self.__options['discard_aborted_uploads']:
            #  uzenet=u'f?jl m?ret elt?r?s file_size='+unicode(file_size) +  u' ufile[size]=' +  unicode(ufile['size'])
            #  wlog(mname,0,uzenet,4)
            #  self.__options['upload_dir'].gfs.delete(new_file_id)
            #  ufile['error'] = 'abort'
    
            
            #ufile['name'].replace(" ", "%20")
            ufile['delete_url'] = self.__options['script_url'] +u'?file='+to_unicode_or_bust(ufile['name'])+u'&dir_id='+str(self.__options['dir_id'])+u'&fileid='+str(ufile['id'])                 
            ufile['delete_type'] = 'DELETE'       
          else:
            ufile['error'] = error
    else:
      ufile['error'] = error

    ufiles.append(ufile)
    #return json.dumps([dict(**ufiles)])
    return json.dumps(ufiles)


  def GET(self):
    mname=u'uploads.UploadHandler.GET'
    #uzenet=u'elindult! input='+unicode(web.input())
    #wlog(mname,0,uzenet,4)
    i=web.input(dir_id=None,file=None)  
    if i.dir_id:
      jogok=projects.getcurdiraccess(i.dir_id)
      info=[]
      if not jogok is None:
        if u'read' in jogok or u'write' in jogok or u'dir' in jogok:
          #uzenet=u'elindult! van dir_id='+unicode(i.dir_id)
          #wlog(mname,0,uzenet,4)
          # van dir_id , be kell ?ll?tani a config url-t
          cur_dir=getDirById(i.dir_id,web.ctx.session.selected_prj)          
          self.__options['dir_id']=i.dir_id
          self.__options['cur_dir']=cur_dir['fullpath']
          griddir=gridfile.griddir(prj_id=web.ctx.session.selected_prj,dir_id=self.__options['dir_id'],showdeleted=web.ctx.session.showdeleted)  
          self.__options['upload_dir']= griddir
          self.__options['upload_url']= to_unicode_or_bust(u'/projectfiles')
          self.__options['image_versions']['thumbnail']['upload_dir']=griddir.gfs_thumbnail 
          self.__options['image_versions']['thumbnail']['upload_uri']= to_unicode_or_bust(u'/thumbnails'+ cur_dir['fullpath']+u'/')
          unlock_expired_locked_files()
    
        if i.file:
          file_name = os.path.basename(i.file)
          #file_name = strip_path_and_sanitize(request.vars.file)
          info = self.__get_file_object(file_name)
        else:
          filename = None
          info = self.__get_file_objects()   
    
    web.header('Content-Type', 'application/json')  
    return  json.dumps(info)

  def POST(self):
    mname=u'uploads.UploadHandler.POST'              
    uzenet=u'elindult!'
    wlog(mname,0,uzenet,4)
    if web.ctx.env.has_key('HTTP_X_FILE_NAME'):
      http_x_file_name=web.ctx.env['HTTP_X_FILE_NAME']
    else:
      http_x_file_name=None
    if web.ctx.env.has_key('HTTP_X_FILE_TYPE'):
      http_x_file_type=web.ctx.env['HTTP_X_FILE_TYPE']
    else:
      http_x_file_type='unknown'
        
    i=web.input(dir_id=None,files={})
    #print_env()
    #uzenet=u'web.input='+str(i) #+' http_x_file_name='+str(http_x_file_name)
    #wlog(mname,0,uzenet,4)
    upload = {}
    upload['error'] = False
    if i.dir_id:
      jogok=projects.getcurdiraccess(i.dir_id)
      info=[]
      if not jogok is None:
        if u'write' in jogok or u'dir' in jogok:
          # van dir_id , be kell ?ll?tani a config url-t
          #uzenet=u'van dir_id='+unicode(i.dir_id)
          #wlog(mname,0,uzenet,4)
          cur_dir=getDirById(i.dir_id,web.ctx.session.selected_prj)
          if not cur_dir is None:
            self.__options['dir_id']= cur_dir['_id']
            self.__options['cur_dir']=cur_dir['fullpath']
            griddir=gridfile.griddir(prj_id=web.ctx.session.selected_prj,dir_id=self.__options['dir_id'],showdeleted=web.ctx.session.showdeleted)  
            self.__options['upload_dir']= griddir                                                                                 
            self.__options['upload_url']=  to_unicode_or_bust(u'/projectfiles'+cur_dir['fullpath']+u'/')            
                          
            if i['files'].value:
              #uzenet=u'van file='+unicode(i.files)
              #wlog(mname,0,uzenet,4)
                    
              #upload['data']= i['files'].value
              upload['data']= i['files'].file #.read()  # ez a mem?ri?ba kezeli a f?jl
              #upload['size'] = web.intget(web.ctx.env.get('CONTENT_LENGTH'), 0) #False #upload.data.file.tell()
              upload['size'] =None #len(upload['data'])
              upload['name']= to_unicode_or_bust(i['files'].filename) #.decode("utf-8")
              ext=upload['name'].split(".")[-1].lower()
              upload['type']='text/plain'
              if config.mimetypes.has_key(ext):
                 # el?sz?r megpr?b?lom a mime config alapj?n   
                 upload['type'] = config.mimetypes[ext]
              
              # upload['file'] = upload_file.file
              # For the moment don't handle multiple files in one POST
              if not http_x_file_name is None :
                uzenet=u'van http_x_file_name='+unicode(http_x_file_name)+u' HTTP_X_FILE_SIZE='+str(long(web.ctx.env['HTTP_X_FILE_SIZE']))
                wlog(mname,0,uzenet,4)
                info = self.__handle_file_upload(
                              upload['data'],
                              http_x_file_name,
                              long(web.ctx.env['HTTP_X_FILE_SIZE']),
                              http_x_file_type,
                              upload['error'],
                              blob=True
                              )
                if  info is False:
                    #uzenet=u'm?g nincs meg az eg?sz f?jl vissza a POST ciklusba'
                    #wlog(mname,0,uzenet,4)                    
                    return (json.dumps({}))           
              else:
                #uzenet=u'nincs http_x_file_name='+unicode(i.http_x_file_name)
                #wlog(mname,0,uzenet,4)
                info = self.__handle_file_upload(
                              upload['data'],
                              upload['name'],
                              upload['size'],
                              upload['type'],
                              upload['error'],
                              blob=False
                          )
              uzenet=u'post vissza='+str(info)
              wlog(mname,0,uzenet,4)
              # j?het az ?zenet a t?bbi kliensnek, a f?jllista friss?t?s?hez websocket
              if config.websocket:
                vissza=broadcast_dir(i.dir_id)
                if vissza==False:
                  uzenet='websocket broadcast nem siker?lt'
                  wlog(mname,0,uzenet,4)
              #j?het az email ?rtes?t?s a usereknek
              data=json.loads(info)
              ufile=data[0]
              actfile=griddir.filecoll.find_one({'_id':ObjectId(ufile['id'])})
              meret=fformatFileSize(actfile['length'])
              uzenet='actfile meret='+str(meret)
              wlog(mname,0,uzenet,4)
              users.sendMail_NewUpload(web.ctx.session.uid,web.ctx.session.selected_prj,cur_dir['_id'],actfile)
              ev=logs.event(u'?j f?jl felt?lt?s')
              ev.data[u'modul']=mname
              ev.data[u'filename']=unicode(actfile['filename'])
              ev.data[u'fileid']=unicode(actfile['_id'])
              ev.data[u'm?ret']=meret
              ev.data[u'contentType']=unicode(actfile['contentType'])               
              ev.save()                        
              web.header('Content-Type', 'application/json')
              return info
            else:
              #nincs file info
              vissza={}
              info=json.dumps([dict(**vissza)])              
          else:
            ev=logs.event(u'felt?lt?s jogosults?g-hiba')
            ev.data[u'modul']=mname
            ev.data[u'jogok']=unicode(jogok)
            ev.data[u'cur_dir']='nem meg?llap?that?'               
            ev.save()
            vissza={}
            vissza['url']= u'nincs jogosults?ga'
            vissza['name'] = u'nincs jogosults?ga'
            vissza['size'] = int(0)
            vissza['type'] = 'hiba'
            vissza['error'] = 'notallowed'
            info=json.dumps([dict(**vissza)])
        else:
            ev=logs.event(u'felt?lt?s jogosults?g-hiba')
            ev.data[u'modul']=mname
            ev.data[u'jogok']=unicode(jogok)
            ev.data[u'cur_dir']=cur_dir['fullpath']               
            ev.save()
            vissza={}
            vissza['url']= u'nincs jogosults?ga'
            vissza['name'] = u'nincs jogosults?ga'
            vissza['size'] = int(0)
            vissza['type'] = 'hiba'
            vissza['error'] = 'notallowed'
            info=json.dumps([dict(**vissza)])                                              
      else:
        vissza={}
        vissza['url']= u'nincs jogosults?ga'
        vissza['name'] = u'nincs jogosults?ga'
        vissza['size'] = int(0)
        vissza['type'] = 'hiba'
        vissza['error'] = 'notallowed'
        info=json.dumps([dict(**vissza)])
      
      web.header('Content-Type', 'application/json')
      return info


  def DELETE(self):
      mname=u'uploads.UploadHandler.DELETE'              
      uzenet=u'elindult!'
      wlog(mname,0,uzenet,4)
      i=web.input(file=None,dir_id=None,fileid=None)
      
      success= False
      dir_error = False
      info={}
      if i.dir_id:
        jogok=projects.getcurdiraccess(i.dir_id)       
        if not jogok is None:
          if u'write' in jogok or u'dir' in jogok:
             cur_dir=getDirById(i.dir_id,web.ctx.session.selected_prj)
             self.__options['dir_id']=  i.dir_id
             self.__options['cur_dir']=cur_dir['fullpath']
             griddir=gridfile.griddir(prj_id=web.ctx.session.selected_prj,dir_id=self.__options['dir_id'],showdeleted=web.ctx.session.showdeleted)  
             self.__options['upload_dir']= griddir            
            
             self.__options['image_upload_dir']= (config.projdir + cur_dir['fullpath']+ u'/thumbnails/').encode("utf-8")                     
            
             if i.file and i.fileid:
                i.fileid=ObjectId(i.fileid)                                                                               
                gfs=self.__options['upload_dir'].gfs
                filecoll=self.__options['upload_dir'].filecoll
                
                success = gfs.exists(i.fileid)       
                if success:
                  try :
                    mydeleted={'deleted':True,'uid':web.ctx.session.uid,'time':time.time()}
                    myfile=filecoll.find_one({'_id':ObjectId(i.fileid)})
                    if to_unicode_or_bust(myfile['name'])== to_unicode_or_bust(i.file):
                      myfile['deleted']=mydeleted
                      filecoll.update({'_id': i.fileid}, myfile, safe=True) 
                      info['succes']=True
                      info['error'] = None
                      uzenet=u't?rl?s sikeres'
                      wlog(mname,0,uzenet,1)
                      ev=logs.event(u'f?jl t?rl?s')
                      ev.data[u'modul']=mname
                      ev.data[u'filename']=unicode(myfile['filename'])
                      ev.data[u'fileid']=unicode(myfile['_id'])                   
                      ev.data[u'contentType']=unicode(myfile['contentType'])
                      ev.data[u'm?ret']=fformatFileSize(myfile['length'])               
                      ev.save()
                      # j?het az ?zenet a t?bbi kliensnek, a f?jllista friss?t?s?hez websocket
                      vissza=broadcast_dir(i.dir_id)
                      if vissza==False:
                        uzenet='websocket broadcast nem siker?lt'
                        wlog(mname,0,uzenet,4)
                    else:
                     info['succes']=False
                     info['error'] = 'notallowed'
                     uzenet=u't?rl?s sikertelen, id <> name ellentmond?s'
                     wlog(mname,2,uzenet,1)     
                  except:
                     info['succes']=False
                     info['error'] = 'notallowed'
                     uzenet=u't?rl?s sikertelen'
                     wlog(mname,2,uzenet,1)
                     ev=logs.event(u'f?jl t?rl?s-hiba')
                     ev.data[u'modul']=mname
                     ev.data[u'nem v?rt hiba']=True
                     ev.data[u'filename']=to_unicode_or_bust(i.file)
                     ev.data[u'fileid']=to_unicode_or_bust(i.fileid)                                  
                     ev.save()  
                else:
                  uzenet=u'f?jl nem tal?lhat? a gridfs-ben'
                  wlog(mname,2,uzenet,1)
                  info['succes']=False
                  info['error'] = 'no found'
                  ev=logs.event(u'f?jl t?rl?s-hiba')
                  ev.data[u'modul']=mname
                  ev.data[u'nem tal?lhat?']=True
                  ev.data[u'filename']=to_unicode_or_bust(i.file)
                  ev.data[u'fileid']=to_unicode_or_bust(i.fileid)                                  
                  ev.save()           
          else:
            # nincs joga
            info['succes']=False
            info['error'] = 'notallowed'
            uzenet=u't?rl?s sikertelen, nincs joga'
            wlog(mname,2,uzenet,1)
            ev=logs.event(u'f?jl t?rl?s-hiba')
            ev.data[u'modul']=mname
            ev.data[u'nincs joga']=True
            ev.data[u'filename']=to_unicode_or_bust(i.file)
            ev.data[u'fileid']=to_unicode_or_bust(i.fileid)                                  
            ev.save()     
        else:
         # nincs joga
         info['succes']=False
         info['error'] = 'notallowed'
         uzenet=u't?rl?s sikertelen, nincs joga'
         wlog(mname,2,uzenet,1)
         ev=logs.event(u'f?jl t?rl?s-hiba')
         ev.data[u'modul']=mname
         ev.data[u'nincs joga']=True
         ev.data[u'filename']=to_unicode_or_bust(i.file)
         ev.data[u'fileid']=to_unicode_or_bust(i.fileid)                                  
         ev.save()       
      
      web.header('Content-Type', 'application/json')
      return json.dumps(success)



 
           

Reply via email to