Help

0

How to download a file with button that executes a method in odoo 10?

Avatar
Samo Arko

I've got a wizard with it I want to create and download a file. The file will be gotten from a selection. It can be a qweb report, xml, xlst, ... .

When the button is clicked the method generates the selected file. I want it to pass to the browser for download. I know I can save the file in a binary field, but then the user needs to click on it, so I want to skip this step.

I know that I can download reports with

<button name="%(action_of_the_qweb_report)d" string="Get Document" type="action"/>

and from the odoo "website" when i get it from ir.attachments:

fileheaders = [
	('Content-Type', tmp_file[0].file_mimetype),
	('Content-Length', len(downlaod_file)),
	('Content-Disposition', 'attachment; filename="{}"'.format(tmp_file[0].name))
]

return request.make_response(downlaod_file, headers=fileheaders)

But I would like to do this from a odoo module. The problem is that files can be different types and some of them like xml are generated with python scripts.

So is there a way to just pass the file to the browser?

1 Comment
Avatar
Discard
2 Answers
2
Avatar
Eman Abdulmalik
Best Answer

Hello,

Use something like below, it will automatically download the file:

import base64
# output is where you have the content of your file, it can be
# any type of content
output 
# encode
result = base64.b64encode(output.read())
# get base url
base_url = self.env['ir.config_parameter'].get_param('web.base.url')
attachment_obj = self.env['ir.attachment']
# create attachment
attachment_id = attachment_obj.create(
{'name': "name", 'datas_fname': 'name.file_ext', 'datas': result})
# prepare download url
download_url = '/web/content/' + str(attachment_id.id) + '?download=true'
# download
return {
"type": "ir.actions.act_url",
"url": str(base_url) + str(download_url),
"target": "new",
}
Avatar
Discard