Skip to content

Instantly share code, notes, and snippets.

@yasmanycastillo
Last active August 30, 2023 14:46
Show Gist options
  • Save yasmanycastillo/7e7002205ef70d7e90d3985b74762fe6 to your computer and use it in GitHub Desktop.
Save yasmanycastillo/7e7002205ef70d7e90d3985b74762fe6 to your computer and use it in GitHub Desktop.
Odoo: How to download a file immediately from wizard
# -*- coding: utf-8 -*-
from odoo import http
from odoo.http import request
from odoo.addons.web.controllers.main import serialize_exception,content_disposition
import base64
class Binary(http.Controller):
@http.route('/web/binary/download_document', type='http', auth="public")
@serialize_exception
def download_document(self, model, id, filename=None, **kw):
""" Download link for files stored as binary fields.
:param str model: name of the model to fetch the binary from
:param str field: binary field
:param str id: id of the record from which to fetch the binary
:param str filename: field holding the file's name, if any
:returns: :class:`werkzeug.wrappers.Response`
"""
record = request.env[model].browse(int(id))
binary_file = record.binary_file_name # aqui colocas el nombre del campo binario que almacena tu archivo
filecontent = base64.b64decode(binary_file or '')
content_type, disposition_content = False, False
if not filecontent:
return request.not_found()
else:
if not filename:
filename = '%s_%s' % (model.replace('.', '_'), id)
content_type = ('Content-Type', 'application/octet-stream')
disposition_content = ('Content-Disposition', content_disposition(filename))
return request.make_response(filecontent, [content_type,
disposition_content])
# Este es la funcion que debes agregar a tu clase
@api.multi
def download(self):
path = "/web/binary/download_document?"
model = "nombre.de.tu.modelo"
filename = "Nombre del archivo"
self.print_report() # esta es la funcion que genera mi archivo y lo almacena en el campo binario
url = path + "model={}&id={}&filename={}.xls".format(
model, self.id, filename)
return {
'type' : 'ir.actions.act_url',
'url': url,
'target': 'self',
'tag': 'reload',
}
# Ojo, al descargar el archivo el wizard se queda frizado, si resuelves como recargarlo me dejas saber
@umiphos
Copy link

umiphos commented Mar 26, 2019

@yasmanycastillo if you create e new target(target: new) you can solve that froze problem

@medosobh
Copy link

medosobh commented Aug 20, 2023

hi, good code,
what is """def download(self):""" for?

@medosobh
Copy link

i try to integrate in my portal class so , i expect that the return will popup a "save file as"?
is that correct?

@medosobh
Copy link

many thanks , it works :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment