python 使用 odoo10 客户端上传文件接口

一丶上传单个文件 保存到本地文件夹

    # 文件上传  保存到本地文件夹
    @http.route('/api/event/fileupload', type='http', auth="none", methods=['POST'], csrf=False)
    def upload_file(self, redirect=None, **kw):
        cr, uid, context, pool = request.cr, request.uid, request.context, request.registry
        values = request.params.copy()

        try:
          
            file_dir = os.path.join(BASE_DIR, 'upload')
            if not os.path.exists(file_dir):
                os.makedirs(file_dir)
            f = request.httprequest.files['cfile']  # 从表单的file字段获取文件,myfile为该表单的name值

            if f and EventHome.allowed_file(f.filename):  # 判断是否是允许上传的文件类型
                fname = secure_filename(f.filename)
                print fname
                ext = fname.rsplit('.', 1)[1]  # 获取文件后缀
                unix_time = int(time.time())
                new_filename = str(unix_time) + '.' + ext  # 修改了上传的文件名
                f.save(os.path.join(file_dir, new_filename))  # 保存文件到upload目录
                token = base64.b64encode(new_filename)
                print token
            
                return '上传成功'
            else:
                return '上传失败'
              
        except Exception, e:
            print  e
           return '上传失败'

    # 用于判断文件后缀
    @classmethod
    def allowed_file(filename):
        for num in ALLOWED_EXTENSIONS:
            if (filename.endswith(ALLOWED_EXTENSIONS[num])):
                return True
        return False

二丶上传多个文件保存到本地数据库

@http.route('/api/event/addevent', type='http', auth="none", methods=['POST'], csrf=False)
    def addevent(self, redirect=None, **kw):
        cr, uid, context, pool = request.cr, request.uid, request.context, request.registry
        values = request.params.copy()
     
        try:
     
            results = []
            # 获取数据库名称
            dbname = cr.dbname
          
            ## 获取文件
            # f = request.httprequest.files['sfile']  # 从表单的file字段获取文件,sfile为该表单的name值
            ##  保存文件
            Attachments = request.env['ir.attachment']#ir.attachment 附件表名
            attachments = request.env['ir.attachment']
            for c_file in request.httprequest.files.getlist('sfile'):
                data = c_file.read()
                try:
                    image = Image.open(cStringIO.StringIO(data))
                    w, h = image.size
                    # if  image.format in ('PNG', 'JPEG'):#根据业务需求在此处做文件类型判断
                    data = tools.image_save_for_web(image)
                except IOError, e:
                    pass
                attachment = Attachments.sudo(uid).create({
                    'name': c_file.filename,
                    'datas': data.encode('base64'),
                    'datas_fname': c_file.filename,
                    'public': True,  # 此处需设置为true 否则attachments.read  读不到
                    'res_model': 'trt.envent.info',
                })
                attachments += attachment
            uploads = []
            uploads += attachments.read(['name', 'mimetype', 'checksum', 'url'])
            ## 与数据库其他表做关联
            for u in uploads:
                ir_attachment_id = str(u.get("id"))
                sql_query = """INSERT INTO 在此处书写对应的 SQL 语句
                        """
                request.env.cr.execute(sql_query)
            # results = request.env.cr.dictfetchall()

            return '成功'
        except Exception, e:
            print e
            return '失败'

你可能感兴趣的:(python 使用 odoo10 客户端上传文件接口)