Reputation: 394
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?
Upvotes: 1
Views: 1393
Reputation: 394
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
Upvotes: 0
Reputation: 3955
I have no experience with odoo; but:
If you have a bytes variable (binary data), you can read it as a Zipfile with the standard python libraries using io.BytesIO and zipfile:
from io import BytesIO
import zipfile
# I assume ths contains the zipfile uploaded by the user.
uploaded_zipfile = fields.Binary(string='ZIP File', store=True)
with BytesIO(uploaded_zipfile) as fp:
userzip = zipfile.ZipFile(fp, 'r')
# You can extract the zip like this:
userzip.extractall()
# Or you can check the contents without extracting all the file
whats_inside_the_zip = userzip.infolist()
Upvotes: 1