Search code examples
pythonodoobinaryfileszipodoo-12

Odoo 12. How to convert Binary File to Zip?


I need to import a zip file that will contain only xml files.

My wizard looks like this:

class ZipImportsWizard(models.Model):
    _name = 'import.zip.dte'

    type = fields.Selection([('purchase', 'Purchases'),('sale', 'Sales'),], string="Type", default="purchase")
    file = fields.Binary(string='ZIP File', store=True)

I need to open this zip file and check the content. If the content is OK, I have to send this to another method.

The problem is, when I upload the file, it converts to a Binary file, so I can't user zipfile library to work with it.

How can I convert this Binary file to a Zip file again to work with it?


Solution

  • I was able to find a solution by myself, but also thanks to @astronautlevel anwers in this Similar question

    from odoo import fields, models, _
    from odoo.exceptions import UserError, ValidationError
    import zipfile
    import tempfile
    
    class ZipImportsWizard(models.Model):
        _name = 'import.zip.dte'
    
        type = fields.Selection([('purchase', 'Purchases'),('sale', 'Sales'),], string="Type", default="purchase")
        file = fields.Binary(string='ZIP File', store=True)
        file_name = fields.Char('File name')
    
        def read_files_from_zip(self):
            file = base64.decodestring(self.zip_file)
            fobj = tempfile.NamedTemporaryFile(delete=False)
            fname = fobj.name
            fobj.write(file)
            fobj.close()
    
            zipzip = self.zip_file
            f = open(fname, 'r+b')  
            data = f.read()
            f.write(base64.b64decode(zipzip))
            pos = data.find(b'\x50\x4b\x05\x06')
            f.seek(pos + 22)
            with zipfile.ZipFile(f, 'r') as zip_file: 
                # do some stuff
                
                f.close()
    
            return