Ir al contenido
Odoo Menú
  • Identificarse
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • TPV para tiendas
    • TPV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en directo
    • e-learning
    Cadena de suministro
    • Inventario
    • Fabricación
    • PLM
    • Compra
    • Mantenimiento
    • Calidad
    Recursos Humanos
    • Empleados
    • Reclutamiento
    • Ausencias
    • Evaluación
    • Referencias
    • Flota
    Marketing
    • Marketing social
    • Marketing por correo electrónico
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyecto
    • Partes de horas
    • Servicio de campo
    • Servicio de asistencia
    • Planificación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Conocimientos
    • WhatsApp
    Aplicaciones de terceros Studio de Odoo Plataforma de Odoo Cloud
  • Industrias
    Comercio al por menor
    • Librería
    • Tienda de ropa
    • Tienda de muebles
    • Tienda de ultramarinos
    • Ferretería
    • Juguetería
    Alimentación y hostelería
    • Bar y pub
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidor de bebidas
    • Hotel
    Inmueble
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión inmobiliaria
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Empresa contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Fabricación
    • Textil
    • Metal
    • Muebles
    • Alimentos
    • Cervecería
    • Regalos de empresas
    Salud y bienestar
    • Club deportivo
    • Óptica
    • Gimnasio
    • Terapeutas
    • Farmacia
    • Peluquería
    Oficios
    • Handyman
    • Hardware y soporte técnico
    • Sistemas de energía solar
    • Zapatero
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin ánimo de lucro
    • Agencia de protección del medio ambiente
    • Alquiler de paneles publicitarios
    • Estudio fotográfico
    • Alquiler de bicicletas
    • Distribuidor de software
    Explorar todos los sectores
  • Comunidad
    Aprender
    • Tutoriales
    • Documentación
    • Certificaciones
    • Formación
    • Blog
    • Podcast
    Potenciar la educación
    • Programa de formación
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtener el software
    • Descargar
    • Comparar ediciones
    • Versiones
    Colaborar
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Convertirse en partner
    • Servicios para partners
    • Registrar tu empresa contable
    Obtener servicios
    • Encontrar un partner
    • Encontrar un asesor fiscal
    • Contacta con un experto
    • Servicios de implementación
    • Referencias de clientes
    • Ayuda
    • Actualizaciones
    GitHub YouTube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicitar una demostración
  • Precios
  • Ayuda

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

  • CRM
  • e-Commerce
  • Contabilidad
  • Inventario
  • PoS
  • Proyecto
  • MRP
All apps
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Ayuda

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

Suscribirse

Reciba una notificación cuando haya actividad en esta publicación

Se marcó esta pregunta
serverclientfiledownloadoutput
5 Respuestas
20300 Vistas
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
Mejor respuesta

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 Mejor respuesta

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
Mejor respuesta

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
¿Le interesa esta conversación? ¡Participe en ella!

Cree una cuenta para poder utilizar funciones exclusivas e interactuar con la comunidad.

Inscribirse
Publicaciones relacionadas Respuestas Vistas Actividad
Upload un fichier téléchargeable par les visiteurs
upload file download
Avatar
0
jun 23
3654
Download External File in Openerp 7.0
external file download
Avatar
3
jun 20
9629
play and dowload mp3 from tree view
file download play
Avatar
0
abr 16
6754
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
ene 25
2226
[10]Download a generated xlsx file by pressing a button Resuelto
file download xlsx odoo10
Avatar
Avatar
Avatar
Avatar
5
abr 23
16853
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento Odoo.sh
  • Ayuda
  • Actualizar
  • Desarrollos personalizados
  • Educación
  • Encontrar un asesor fiscal
  • Encontrar un partner
  • Convertirse en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contacta con nosotros
  • Puestos de trabajo
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Información legal • Privacidad
  • Seguridad
الْعَرَبيّة 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 es un conjunto de aplicaciones de código abierto que cubren todas las necesidades de tu empresa: CRM, comercio electrónico, contabilidad, inventario, punto de venta, gestión de proyectos, etc.

La propuesta única de valor de Odoo es ser muy fácil de usar y totalmente integrado.

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