跳至内容

Odoo实现移动端批量文件上传功能全攻略

随着移动办公的普及,微信公众号、微信小程序、钉钉等移动平台已成为日常办公的重要工具。在这些平台上,用户经常需要上传图片、文档等附件到Odoo系统中。本文将详细介绍如何在Odoo中实现一个安全、高效的批量文件上传接口,并特别优化移动端使用体验。

一、需求分析与设计思路

  1. 在移动办公场景下,文件上传功能需要满足以下核心需求:
  2. 批量上传支持:允许用户一次选择多个文件上传
  3. 移动端友好:适配微信、钉钉等移动端平台的上传特性
  4. 性能优化:处理大文件上传时的效率问题
  5. 安全认证:确保上传接口不会被滥用
  6. 日志记录:完整记录上传过程便于排查问题

二、后端接口

实现以下是完整的批量上传接口实现代码,已针对移动端使用场景进行了优化:

# -*- coding: utf-8 -*-from odoo import http
from odoo.http import request
import werkzeug,json
import logging
import base64
_logger = logging.getLogger(__name__)


class Edoupfile(http.Controller):
    @http.route('/web/edoupfile/upload_attachments', auth='none', cors="*", methods=["POST"], csrf=False)
    def upload_attachments(self, model, id, **kwargs):
        _logger.info("批量上传附件接口")
        # 用户认证,获取用户权限
        apiuser_credential = {
            'login': 'upfile',
            'password':'upfile@2025@upfile',
            'type': 'password'
        }

        myid = request.session.authenticate('codoo18_health', apiuser_credential)
        if myid:
            _logger.info("用户登录成功")

            # 获取请求中的文件列表
            files = request.httprequest.files.getlist('files')
            res_id = int(id)
            # 确保记录存在
            record = request.env[model].browse(res_id).exists()
            _logger.info(f"模型{model}记录{id}为:{record}")
            if not record:
                return werkzeug.exceptions.NotFound()

            # 为每个文件创建附件
            Attachment = request.env['ir.attachment']
            for file in files:
                _logger.info(f"上传的文件为:{file},文件名:{file.filename}")
                file_data = file.read()
                if isinstance(file_data, str):
                    encoded_data = file_data.encode('utf-8').encode('base64')
                elif isinstance(file_data, bytes):
                    encoded_data = base64.b64encode(file_data).decode('ascii')
                else:
                    encoded_data = ''

                attachment = Attachment.create({
                    'name': file.filename,
                    'res_model': model,
                    'res_id': res_id,
                    'datas': encoded_data,
                })
            return request.make_response(json.dumps({'result': True}))

三、代码解析:

  1. 认证机制:使用专用API用户进行认证,避免使用普通用户凭证
  2. CORS支持:设置cors="*"允许跨域请求,适配移动端调用
  3. 批量处理:通过request.httprequest.files.getlist('files')获取多文件
  4. 数据类型处理:智能判断文件数据类型并进行正确的base64编码
  5. 日志记录:关键步骤都添加了日志记录,便于问题排查

四、AIRPOST测试

注意点:

  1. body:选择"form-data"
  2. model:输入类型值
  3. id:输入记录的id
  4. files:这里需要选择“file”

五、注意点

1.odoo是实现单一文件的,要实现批量上传需要使用循环;

2. 循环可以是前端,也可以在后端。

博客
odoo利用EXCEL实现套打