import os import base64 def base_data_product_image(self): """ odoo里批量創建產品,並上傳圖片 圖片為binary類型字段 :param self: :return:# odoo里面附近存儲格式三base64編碼格式的 """ path = "D:\\image_files" # 這里windows環境路徑 filelist = os.listdir(path) product_obj = self.env['product.template'].sudo() i = 1 if not len(filelist): return { "result": "Fail", "msg": "not image!" } for image in filelist: # 這里可以根據后綴來過濾文件類型jpg、png if image.endswith('.png'): with open("D:\\image_files\\%s" % image, "rb") as f: base64_data = base64.b64encode(f.read()) product_obj.create({ "name": "test_product_%s" % str(i), "image_1920": base64_data }) # 文件打開后記得close, # 1、with open()as f;文件打開后會自動關閉 # 2、open(),打開文件不會自動關閉 # 建議都close一下 f.close() i += 1 return { "result": "Success", "msg": "Product create success!" } # 案例2 # 這是針對many2many類型的ir.attachment字段創建的例子 name="test" data_attach = { 'name': name, 'datas': base64.b64encode(content), 'type': 'binary', 'datas_fname': name, 'description': name, 'res_model': 'test_model', 'res_id': '1', } new_attachment = IrAttachment.create(data_attach)
