[英]Odoo 12. How to convert Binary File to Zip?
我需要導入一個僅包含 xml 文件的 zip 文件。
我的向導如下所示:
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)
我需要打開這個 zip 文件並檢查內容。 如果內容沒問題,我必須將其發送到另一個方法。
問題是,當我上傳文件時,它會轉換為二進制文件,因此我無法使用 zipfile 庫來處理它。
如何再次將此二進制文件轉換為 Zip 文件以使用它?
我沒有使用 odoo 的經驗; 但:
如果您有一個 bytes 變量(二進制數據),您可以使用io.BytesIO和zipfile將其作為帶有標准 python 庫的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()
我能夠自己找到解決方案,但也感謝@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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.