Ir al contenido
Odoo Menú
  • Iniciar sesión
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • PdV para tiendas
    • PdV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en vivo
    • eLearning
    Cadena de suministro
    • Inventario
    • Manufactura
    • PLM
    • Compras
    • Mantenimiento
    • Calidad
    Recursos humanos
    • Empleados
    • Reclutamiento
    • Vacaciones
    • Evaluaciones
    • Referencias
    • Flotilla
    Marketing
    • Redes sociales
    • Marketing por correo
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyectos
    • Registro de horas
    • Servicio externo
    • Soporte al cliente
    • Planeación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Artículos
    • WhatsApp
    Aplicaciones externas Studio de Odoo Plataforma de Odoo en la nube
  • Industrias
    Venta minorista
    • Librería
    • Tienda de ropa
    • Mueblería
    • Tienda de abarrotes
    • Ferretería
    • Juguetería
    Alimentos y hospitalidad
    • Bar y pub
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidora de bebidas
    • Hotel
    Bienes inmuebles
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión de bienes inmuebles
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Firma contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Manufactura
    • Textil
    • Metal
    • Muebles
    • Comida
    • Cervecería
    • Regalos corporativos
    Salud y ejercicio
    • Club deportivo
    • Óptica
    • Gimnasio
    • Especialistas en bienestar
    • Farmacia
    • Peluquería
    Trades
    • Personal de mantenimiento
    • Hardware y soporte de TI
    • Sistemas de energía solar
    • Zapateros y fabricantes de calzado
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin fines de lucro
    • Agencia para la protección del medio ambiente
    • Alquiler de anuncios publicitarios
    • Fotografía
    • Alquiler de bicicletas
    • Distribuidor de software
    Descubre todas las industrias
  • Odoo Community
    Aprende
    • Tutoriales
    • Documentación
    • Certificaciones
    • Capacitación
    • Blog
    • Podcast
    Fortalece la educación
    • Programa educativo
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtén el software
    • Descargar
    • Compara ediciones
    • Versiones
    Colabora
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Conviértete en partner
    • Servicios para partners
    • Registra tu firma contable
    Obtén servicios
    • Encuentra un partner
    • Encuentra un contador
    • Contacta a un consultor
    • Servicios de implementación
    • Referencias de clientes
    • Soporte
    • Actualizaciones
    GitHub YouTube Twitter LinkedIn Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicita 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
  • Proyectos
  • 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

OpenERP multiple file upload

Suscribirse

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

Se marcó esta pregunta
widgetuploadmultipleimagescontrollers
10 Respuestas
22908 Vistas
Avatar
Vicious

I'm programming a module in OpenERP to upload multiple images from a folder in one go, using HTML5 input multiple without uploading pictures one at a time and not store them in the database, with the loss of performance that implies, I save them as files, I have a form with a Widget that makes a POST request to a controller, the problem is that it print only the last FileStorage object, when I send more than one, to upload multiple files at a time , however I can not find how to modify it because I do not even like the web client decides to send an object of type FileStorage or other object!

My Widget

<t t-name="HiddenInputFileMulti">
        <div t-attf-class="oe_hidden_input_file #{fileupload_class or ''}" t-att-style="fileupload_style">
            <form class="oe_form_binary_form" t-att-target="fileupload_id" method="POST" enctype="multipart/form-data" action="/web/binary/multi_picture_upload">
                <t t-raw="__content__"/>
                <input type="file" id="files" class="oe_form_binary_file" name="ufile" accept="image/*" multiple=""/>
            </form>
        </div>
    </t>

My controller:

from openerp.addons.web import http as openerpweb
from openerp.addons.web.controllers.main import Binary

@openerpweb.httprequest
    def multi_picture_upload(self, req, ufile):

         print ufile #this print the last FileStorage object, in a dict like :FileStorage: u'tula.gif' ('image/gif')

EDIT:

I say forget that when I print the contents of ufile, It returns a dictionary with a single pair

<FileStorage: u'tula.gif' ('image/gif')>

this is the last picture I sent, and analyzing the request indeed, the web client sends all pictures, but the controller only receives the last, it seems like they just dismiss all previous images ....

3
Avatar
Descartar
Avatar
Vicious
Autor Mejor respuesta

 UPDATE

 By insisting I'll post the code to load more than one file at a time:

In the http.py file must comment a line and add another, in the line 608:

http.py

class HttpRequest(WebRequest):
""" Handler for the ``http`` request type.

matched routing parameters, query string parameters, form_ parameters
and files are passed to the handler method as keyword arguments.

In case of name conflict, routing parameters have priority.

The handler method's result can be:

* a falsy value, in which case the HTTP response will be an
`HTTP 204`_ (No Content)
* a werkzeug Response object, which is returned as-is
* a ``str`` or ``unicode``, will be wrapped in a Response object and
interpreted as HTML

.. _form: http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2
.. _HTTP 204: http://tools.ietf.org/html/rfc7231#section-6.3.5
"""
_request_type = "http"

def __init__(self, *args):
super(HttpRequest, self).__init__(*args)
params = self.httprequest.args.to_dict()
params.update(self.httprequest.form.to_dict())
#params.update(self.httprequest.files.to_dict())
params.update(self.httprequest.files) # Modified line
params.pop('session_id', None)
self.params = params

My controller:

from openerp import http
import simplejson
import time
import os
import StringIO


class Binary_Multi(http.Controller):

@http.route('/web/binary/multi_picture_upload', type="http", auth="public")
def multi_picture_upload(self, req, callback, ufile):
out = """<script language="javascript src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" type="text/javascript">
var win = window.top.window;
win.jQuery(win).trigger(%s, %s);
</script>"""
args = []
for nfile in ufile:
data = nfile.read()
current_dat_time = time.strftime("%d-%m-%Y-%H_%M_%S")
file_name = current_dat_time + "_" + nfile.filename
addons_path = http.addons_manifest['web']['addons_path'] +\
"/web/static/src/img/image_multi/"
if not os.path.isdir(addons_path):
os.mkdir(addons_path)
addons_path += file_name
buff = StringIO.StringIO()
buff.write(data)
buff.seek(0)
file_name = "/web/static/src/img/image_multi/" + file_name
file = open(addons_path, 'wb')
file.write(buff.read())
file.close()
args.append([len(data), file_name, nfile.content_type,
nfile.filename, time.strftime("%m/%d/%Y %H:%M:%S")])
return out % (simplejson.dumps(callback), simplejson.dumps(args))

 Now you can scroll through the list with for loop

but this would cause us a problem, if we upload attachments in fields.Binary.

I modify the core again to use both, my multiple images fields and traditional fields.Binary attachments.

class HttpRequest(WebRequest):
""" Handler for the ``http`` request type.

matched routing parameters, query string parameters, form_ parameters
and files are passed to the handler method as keyword arguments.

In case of name conflict, routing parameters have priority.

The handler method's result can be:

* a falsy value, in which case the HTTP response will be an
`HTTP 204`_ (No Content)
* a werkzeug Response object, which is returned as-is
* a ``str`` or ``unicode``, will be wrapped in a Response object and
interpreted as HTML

.. _form: http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2
.. _HTTP 204: http://tools.ietf.org/html/rfc7231#section-6.3.5
"""
_request_type = "http"

def __init__(self, *args):
super(HttpRequest, self).__init__(*args)
params = self.httprequest.args.to_dict()
params.update(self.httprequest.form.to_dict())
#params.update(self.httprequest.files.to_dict())

str_args = str(args)
# If the request is from my controller,( in tis case, multi_picture_upload)then use modified line
if str_args.find("multi_picture_upload") >=0: #
params.update(self.httprequest.files)
# Else, just use the original line
else:
params.update(self.httprequest.files.to_dict())
params.pop('session_id', None)
self.params = params


sorry that my code is so ugly/akward, and my English so bad. 

1
Avatar
Descartar
Vicious
Autor

Forgot to say that when I print the contents of ufile, I returns a dictionary with a single pair FileStorage: u'tula.gif' ('image/gif') , this is the last picture I sent, and analyzing the request indeed, the web client sends all pictures, but the controller only receives the last, it seems like they just dismiss all previous images ....

Marcin Kieszek

Have you found a solution? I'm also interested in that case.

OdooBot
which case?
I have several post's
El 23/09/14 04:32, Bajkar escribió:
<blockquote cite="mid:1411461174.535656929016113.921812722042857-openerp-55718-forum.post@accounts.odoo.com" type="cite">

Have you found a solution? I'm also interested in that case.

--
Bajkar
Sent by OpenERP S.A. using Odoo about Forum Post False
Vicious
Autor

Excuse me, answered from the email, I found a way to make it work, but modifying the core code

David Myers

@Vicious : I like what you are attempting to do here. However I think another potential idea for the process is as follows: link out to an ftp system, and use that to import the files. Obviously you'll need to enable the storage of files on disk rather than in the database. The improvement that I would like to see is to load in multiple image files into a galery in one hit. If I want to enable a gallery with a lot of images I have to spend a lot of time selecting them... which really agravates me, as my local pc is rather old!

Vicious
Autor

@David Myers I already have it running a gallery, using a multiple charger taking the "multiple" property in html, what you say is completely valid, however my clients are very basic users, for each case, taking pictures with they digital camera, then create a folder on the PC, move all the photos to that folder, and the camera stays empty for the next occasion, then the in the Odoo, to get you out the window to select files for all the selected (Ctrl + E) folder . Yes to upload the photos they had to host them on an FTP, copy the link text and copy and paste these links into a box, I would look like a fool. No posting the solution because from the moment we need to modify some of the core Odoo is not a valid option for everyone, and it's not doing anything fancy. However, OpenERP 7 runs well, need to modify 4 lines, and Odoo 8 also to modify a single line ... the most curious is that the lines change to work on OpenERP 7 are now part of the core of Odoo 8 out the box.

sameer alhwety

@Vicious : can you mention the line in Odoo to make the binary field takes more than file ?

Avatar
AbdelAli MERZOUGUI
Mejor respuesta

I've looking for the same functionality, and i inspired from 'Vicious' answer about werkzeug accepting just one file at once, 

In fact, my goal was uploading different images on product profile, since i could not upload but one file at the time, I suited the next procedure:

1- put images in a zip file

2- upload the zip file 

3- get images in memory

4- create images 

That's it, 

Hope that could help you guys

1
Avatar
Descartar
Avatar
tansadio
Mejor respuesta

Hi, I have this error when i upload a image:

image_data = upload.read()

AttributeError: 'unicode' object has no attribute 'read'

When i call my controllers:

The variable request.params['upload'] contains " <FileStorage: u'ir_attachment_117.jpeg' ('image/jpeg')>", 

I want update field product.template image with this image ir_attachment_117.jpeg. 

I need your HELP!

0
Avatar
Descartar
Vicious
Autor

I post a new anwser!

Vicious
Autor

I post a new anwser!

tansadio

Thanks for your answer!

Avatar
yuri
Mejor respuesta

Vicious, would you like to share the solution even if modify the core I don't mind.

0
Avatar
Descartar
Vicious
Autor

i post a new anwser

¿Le interesa esta conversación? ¡Participe en ella!

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

Registrarse
Publicaciones relacionadas Respuestas Vistas Actividad
Is it possible to upload multiple images for main image of the product? Resuelto
product image upload multiple images
Avatar
Avatar
Avatar
Avatar
4
ene 23
19443
Upload image from website to backend (contact us form)
upload images contactus
Avatar
Avatar
1
nov 23
8667
I Want to upload multiple files in my module Resuelto
upload multiple odoo odoo13
Avatar
Avatar
1
nov 21
16633
[Odoo 14] - Model is not updating via Controller
widget models controllers v14
Avatar
Avatar
1
sept 21
5380
Images corrupted after upload
upload debian images odoo10
Avatar
Avatar
3
nov 17
4898
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento en Odoo.sh
  • Soporte
  • Actualizaciones del software
  • Desarrollos personalizados
  • Educación
  • Encuentra un contador
  • Encuentra un partner
  • Conviértete en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contáctanos
  • Empleos
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • 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 estar 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