Exemple #1
0
 def _to_python(self, value, state=None):
     if isinstance(value, cgi.FieldStorage):
         filename = upload_basename(value.filename)
         if len(filename) > 200:
             raise formencode.Invalid("Filename longer than 200 chars", value, state)
         return value
     else:
         raise formencode.Invalid("Need a file upload", value, state)
Exemple #2
0
    def upload_file(self, id=None):
        self.__setup_box2_code_context(id)
        source = QLStorageSource(config)
        basename = upload_basename(self.form_result['file'].filename)
        errors = {}

        existing_path = self.__file_name_query(c.box2.id, basename)
        if existing_path and not self.form_result['file_id'] == existing_path.id:
            # todo, if existing update path
            errors = dict(file='File with this name already exists for this reader.  Use the Update page.')

        path = "%s_%s" % (int(round(time.time())), basename)
        thefile = self.form_result['file'].file

        filerec = self.__file_id_query(c.box2.id, self.form_result['file_id'])
        new_record = False
        if not filerec:
            filerec = Box2File(box2_id=c.box2.id)
            new_record = True

        filerec.name = basename
        filerec.deleted = False
        filerec.path = path
        filerec.updated = datetime.datetime.now()
        filerec.description = self.form_result['description']
        filerec.mime_type = guess_type(basename)[0] or 'text/plain'


        if errors:
            response = self._upload_base(id)
            return h.render_bootstrap_form(response, errors=errors, error_formatters=h.tw_bootstrap_error_formatters)

        try:
            attachment_dir = self.__upload_file_dir(c.box2)
            if not os.path.exists(attachment_dir):
                os.mkdir(attachment_dir)

            permanent_path = self.__upload_file_path(c.box2, path)
            permanent_file = open(permanent_path, 'wb')
            shutil.copyfileobj(thefile, permanent_file)
            thefile.close()
            permanent_file.close()

            filerec.size = os.stat(permanent_path).st_size
            if new_record:
                Session.add(filerec)
            else:
                Session.merge(filerec)
            Session.commit()
            session['flash'] = 'File uploaded.'
            write_success = True
        except Exception, e:
            session['flash'] = 'Could not upload file: %s' % str(e)
            session['flash_class'] = 'error'
            write_success = False