Skip to Content
Odoo Menú
  • Registra entrada
  • Prova-ho gratis
  • Aplicacions
    Finances
    • Comptabilitat
    • Facturació
    • Despeses
    • Full de càlcul (IA)
    • Documents
    • Signatura
    Vendes
    • CRM
    • Vendes
    • Punt de venda per a botigues
    • Punt de venda per a restaurants
    • Subscripcions
    • Lloguer
    Imatges de llocs web
    • Creació de llocs web
    • Comerç electrònic
    • Blog
    • Fòrum
    • Xat en directe
    • Aprenentatge en línia
    Cadena de subministrament
    • Inventari
    • Fabricació
    • PLM
    • Compres
    • Manteniment
    • Qualitat
    Recursos humans
    • Empleats
    • Reclutament
    • Absències
    • Avaluacions
    • Recomanacions
    • Flota
    Màrqueting
    • Màrqueting Social
    • Màrqueting per correu electrònic
    • Màrqueting per SMS
    • Esdeveniments
    • Automatització del màrqueting
    • Enquestes
    Serveis
    • Projectes
    • Fulls d'hores
    • Servei de camp
    • Suport
    • Planificació
    • Cites
    Productivitat
    • Converses
    • Validacions
    • IoT
    • VoIP
    • Coneixements
    • WhatsApp
    Aplicacions de tercers Odoo Studio Plataforma d'Odoo al núvol
  • Sectors
    Comerç al detall
    • Llibreria
    • Botiga de roba
    • Botiga de mobles
    • Botiga d'ultramarins
    • Ferreteria
    • Botiga de joguines
    Food & Hospitality
    • Bar i pub
    • Restaurant
    • Menjar ràpid
    • Guest House
    • Distribuïdor de begudes
    • Hotel
    Immobiliari
    • Agència immobiliària
    • Estudi d'arquitectura
    • Construcció
    • Gestió immobiliària
    • Jardineria
    • Associació de propietaris de béns immobles
    Consultoria
    • Empresa comptable
    • Partner d'Odoo
    • Agència de màrqueting
    • Bufet d'advocats
    • Captació de talent
    • Auditoria i certificació
    Fabricació
    • Textile
    • Metal
    • Mobles
    • Menjar
    • Brewery
    • Regals corporatius
    Salut i fitness
    • Club d'esport
    • Òptica
    • Centre de fitness
    • Especialistes en benestar
    • Farmàcia
    • Perruqueria
    Trades
    • Servei de manteniment
    • Hardware i suport informàtic
    • Sistemes d'energia solar
    • Shoe Maker
    • Serveis de neteja
    • Instal·lacions HVAC
    Altres
    • Nonprofit Organization
    • Agència del medi ambient
    • Lloguer de panells publicitaris
    • Fotografia
    • Lloguer de bicicletes
    • Distribuïdors de programari
    Browse all Industries
  • Comunitat
    Aprèn
    • Tutorials
    • Documentació
    • Certificacions
    • Formació
    • Blog
    • Pòdcast
    Potenciar l'educació
    • Programa educatiu
    • Scale-Up! El joc empresarial
    • Visita Odoo
    Obtindre el programari
    • Descarregar
    • Comparar edicions
    • Novetats de les versions
    Col·laborar
    • GitHub
    • Fòrum
    • Esdeveniments
    • Traduccions
    • Converteix-te en partner
    • Services for Partners
    • Registra la teva empresa comptable
    Obtindre els serveis
    • Troba un partner
    • Troba un comptable
    • Contacta amb un expert
    • Serveis d'implementació
    • Referències del client
    • Suport
    • Actualitzacions
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Programar una demo
  • Preus
  • Ajuda

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Comptabilitat
  • Inventari
  • PoS
  • Projectes
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
Ajuda

How to create a file on the server, and download it on the client?

Subscriure's

Get notified when there's activity on this post

This question has been flagged
serverclientfiledownloadoutput
5 Respostes
20289 Vistes
Avatar
Eric

Hello, I need to output a file on the server so that users can download it on their machines.  How can I do this in Odoo?

1
Avatar
Descartar
Sehrish

I hope you are looking this: http://learnopenerp.blogspot.com/2020/06/write-binary-data-nto-zip-file-and-downlaod-it-on-button-click-in-odoo.html

Avatar
Bole
Best Answer

Probably the best solution is to create it server side, base64 encode it, and attach it to relevant document... 
For simplicity here is example.. 
Let's say you want some xml report... 
1. you generate the xml_string then you pass it to a method like this:

def _attach_xml_file(self, cr, uid, ids, xml_string, context=None):  

      import base64

        assert len(ids) == 1, "Only one ID accepted"
        model_obj= self.pool.get('your.model')          # the model of record you want file attached
        record_obj= model_obj.browse(cr, uid, ids[0]) # actual record to wich you attach file
        file_name = 'name_your_file_here.xml'
        attach_name = file_name
        attach_obj = self.pool.get('ir.attachment')
        context.update({'default_res_id': ids[0], 
                                 'default_res_model': 'your.model'})

        attach_id = attach_obj.create(cr, uid, {'name': attach_name, 
                                                'datas': base64.encodestring(xml_string), 
                                                'datas_fname': file_name}, context=context)
        return attach_id

2. now yout file is attached to "record_obj" of "your.model"
Example: you need some additional conditions in xml form attached to sale order  then your.model = sale.order, and record_obj is the id of selected order... 
3. File is accesible for download to client via Attachment button (top of order view)

 

hope it helps...

1
Avatar
Descartar
Eric
Autor

Thank you for your reply. In my case I wanted to stay away from the ir.attachments model, but all i needed to do was read the file I created into a string variable. Then pass the string into the base64.encodestring(string_variable). Now I am able to download the file from the new model that I created. Thank you for your help

Avatar
Eric
Autor Best Answer

First I added these two lines in the top of my python file

import io # used to output a file with exported data

import base64 # used to encode the contents of the exported file in binary form. this is used to download the file once its created

 

Fields Added in _columns { } on the python file:

"file_name": fields.char( "File Name" )

"file_binary": fields.binary( "Binary File" )

 

Code written in create()

I used the create method to save the new record with the binary data

def create(self, cr, uid, vals, context=None):

    # code goes in here...

 

Create the file:

Then I created the file like this in write mode

file_obj = open( "c:\Users\name_of_file.txt", "w")

file_obj.write( "some sample text..." )

file_obj.close()

 

Read file and encode with base64

# Re open the file_obj in read mode

file_obj = open( "c:\Users\name_of_file.txt", "r")

file_string = file_obj.read()

vals[ "file_binary" ] = base64.encodestring( file_string )   # Assuming this is in the create() and using the vals{ } to save the data

file_obj.close()

 

Create record with the filename and binary file data

new_id = super(current_model_used, self).create(cr, uid, vals, context)

 

XML form and tree views

Add the new fields on the form and tree views like this. This way when you download the file, then the file name will be used.

< field name="file_name" />

< field name="file_binary" filename="file_name" /> <!-- notice the filename attribute. Use this to set the file name with "file_name"  field-->

 

The end. Hope this helps!

 

1
Avatar
Descartar
Avatar
Bole
Best Answer

Probably the best solution is to create it server side, base64 encode it, and attach it to relevant document... 
For simplicity here is example.. 
Let's say you want some xml report... 
1. you generate the xml_string then you pass it to a method like this:

def _attach_xml_file(self, cr, uid, ids, xml_string, context=None):

 import base64

        assert len(ids) == 1, "Only one ID accepted"
        model_obj= self.pool.get('your.model')          # the model of record you want file attached
        record_obj= model_obj.browse(cr, uid, ids[0]) # actual record to wich you attach file
        file_name = 'name_your_file_here.xml'
        attach_name = file_name
        attach_obj = self.pool.get('ir.attachment')
        context.update({'default_res_id': ids[0], 
                                 'default_res_model': 'your.model'})

        attach_id = attach_obj.create(cr, uid, {'name': attach_name, 
                                                'datas': base64.encodestring(xml_string), 
                                                'datas_fname': file_name}, context=context)
        return attach_id

1
Avatar
Descartar
Enjoying the discussion? Don't just read, join in!

Create an account today to enjoy exclusive features and engage with our awesome community!

Registrar-se
Related Posts Respostes Vistes Activitat
Upload un fichier téléchargeable par les visiteurs
upload file download
Avatar
0
de juny 23
3651
Download External File in Openerp 7.0
external file download
Avatar
3
de juny 20
9628
play and dowload mp3 from tree view
file download play
Avatar
0
d’abr. 16
6753
How can I make it so that when we click on a button on a website, a pdf file is automatically downloaded?
file download button_url PDF
Avatar
Avatar
Avatar
Avatar
3
de gen. 25
2223
[10]Download a generated xlsx file by pressing a button Solved
file download xlsx odoo10
Avatar
Avatar
Avatar
Avatar
5
d’abr. 23
16848
Community
  • Tutorials
  • Documentació
  • Fòrum
Codi obert
  • Descarregar
  • GitHub
  • Runbot
  • Traduccions
Serveis
  • Allotjament a Odoo.sh
  • Suport
  • Actualització
  • Desenvolupaments personalitzats
  • Educació
  • Troba un comptable
  • Troba un partner
  • Converteix-te en partner
Sobre nosaltres
  • La nostra empresa
  • Actius de marca
  • Contacta amb nosaltres
  • Llocs de treball
  • Esdeveniments
  • Pòdcast
  • Blog
  • Clients
  • Informació legal • Privacitat
  • Seguretat
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo és un conjunt d'aplicacions empresarials de codi obert que cobreix totes les necessitats de la teva empresa: CRM, comerç electrònic, comptabilitat, inventari, punt de venda, gestió de projectes, etc.

La proposta única de valor d'Odoo és ser molt fàcil d'utilitzar i estar totalment integrat, ambdues alhora.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now