Download zip file on button click in Odoo
The scenario is we have an attachment or file (in binary format) in our database (PostgreSQL) and we want to download that file or attachment in .zip or .rar extension on button click. To do that I am going to use python library named "zipfile". This is python standard library, so we don't need to install it explicitly.
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
@api.multi | |
def odoo_button_click(self): | |
print('****************odoo_button_click******************') | |
import os, zipfile | |
# function to convert binary data | |
def isBase64_decodestring(s): | |
try: | |
return base64.decodestring(s) | |
except Exception as e: | |
raise ValidationError('Error:', +str(e)) | |
# getting working module where your current python file (model.py) exists | |
path = os.path.dirname(os.path.realpath(__file__)) | |
# creating dynamic path to create zip file | |
file_name = "static\\src\\any_folder\\" + str(self.field_1.name.strip().replace(' ', '_').replace('-', '_')) + '_' + str(self.name.strip().replace(' ', '_')) | |
file_name_zip = file_name+".rar" | |
zipfilepath = os.path.join(path, file_name_zip) | |
# creating zip file in above mentioned path | |
zip_archive = zipfile.ZipFile(zipfilepath, "w") | |
# creating file name (like example.txt) in which we have to write binary field data or attachment | |
object_name = self.binary_field_name | |
object_handle = open(object_name, "w") | |
# writing binary data into file handle | |
object_handle.write(isBase64_decodestring(self.attachment)) | |
object_handle.close() | |
# writing file into zip file | |
zip_archive.write(object_name) | |
zip_archive.close() | |
# code snipet for downloading zip file | |
return { | |
'type': 'ir.actions.act_url', | |
'url': str('/your_module/static/src/any_folder/'+str(zip_file_name_with_rar_extension), | |
'target': 'new', | |
} |
Don,t forgot to share, keep sharing keep learning
7 Comments
object_name = self.binary_field_name
ReplyDeletehere what binary_field_name contains can you please tell me
in odoo binary field looks like
Deleteattachment = fields.Binary(string='Attachment')
that contains files
hi, is there a way to download a file from other website and pass to user, without save to server?
ReplyDeleteyes you can use xml-rpc for this
DeleteHello dear, please whats the difference between the self.attachment and self.binary_field_name?
ReplyDeletedear there is no difference, actually self.attachment is a binary field name nothing else...
Deleteattachment = fields.Binary(string='Attachment')
Hello dear, please; whats de difference between self.binary_field_name and self.attachment?
ReplyDelete