Last active
August 13, 2022 15:59
-
-
Save 3mrdev/c0c92cfe388e3713d6416edb84fb1fd8 to your computer and use it in GitHub Desktop.
Controller to expose Odoo binary data to readable files extensions to be displayed on browsers and executed by urls in web page (Images/Audio/PDFs..etc)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import json | |
import logging | |
import base64 | |
from odoo import http, tools, _ | |
from odoo.http import request | |
_logger = logging.getLogger(__name__) | |
class UtilsApi(http.Controller): | |
@http.route(['/util/image/<string:model_name>/<int:uid>'], type='http', auth='public', website=True,method=['GET'], csrf=False, cors='*') | |
def get_image(self, model_name=False, uid=False, **get): | |
return self.getFile(model_name, uid, "image", 'image/png') | |
@http.route(['/util/audio/<string:model_name>/<int:uid>'], type='http', auth='public', website=True,method=['GET'], csrf=False, cors='*') | |
def get_audio(self, model_name=False, uid=False, **get): | |
return self.getFile(model_name, uid, "voice", 'audio/aac') | |
@http.route(['/util/pdf/<string:model_name>/<string:uuid>'], type='http', auth='public', website=True,method=['GET'], csrf=False, cors='*') | |
def get_pdf(self, model_name=False, uuid=False, **get): | |
uid = request.env[model_name].sudo().search([('uuid', '=', str(uuid))]) | |
return self.getFile(model_name, uid.id, "report", 'application/pdf') | |
def getFile(self, model_name=False, id=False, field_name = "image", content_type = 'image/png'): | |
if not model_name or not id: | |
return request.make_response( | |
json.dumps({"response": "Fail", "success": False, "message": "model_name or id not provided"}), | |
[('Content-Type', 'application/json'), ] | |
) | |
else : | |
data = request.env[model_name].sudo().search([('id', '=', int(id))]) | |
if data and data[0][field_name]: | |
return request.make_response( | |
base64.b64decode(data[0][field_name]), | |
[('Content-Type', content_type),] | |
) | |
else: | |
return request.make_response( | |
json.dumps({"response": "Fail", "success": False, "message": "data not found"}), | |
[('Content-Type', 'application/json'),] | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To display the content of a field every route has its default field name you can change it if you want
Example of the Image URL:
Example of the Audio URL:
Example of the PDF URL:
Example of displaying image in html tag on your reports or form views:
<img src="http://localhost:8069/util/image/res.partner/1"/>