Pular para o conteúdo
Odoo Menu
  • Entrar
  • Experimente grátis
  • Aplicativos
    Finanças
    • Financeiro
    • Faturamento
    • Despesas
    • Planilhas (BI)
    • Documentos
    • Assinar Documentos
    Vendas
    • CRM
    • Vendas
    • PDV Loja
    • PDV Restaurantes
    • Assinaturas
    • Locação
    Websites
    • Criador de Sites
    • e-Commerce
    • Blog
    • Fórum
    • Chat ao Vivo
    • e-Learning
    Cadeia de mantimentos
    • Inventário
    • Fabricação
    • PLM - Ciclo de Vida do Produto
    • Compras
    • Manutenção
    • Qualidade
    Recursos Humanos
    • Funcionários
    • Recrutamento
    • Folgas
    • Avaliações
    • Indicações
    • Frota
    Marketing
    • Redes Sociais
    • Marketing por E-mail
    • Marketing por SMS
    • Eventos
    • Automação de Marketing
    • Pesquisas
    Serviços
    • Projeto
    • Planilhas de Horas
    • Serviço de Campo
    • Central de Ajuda
    • Planejamento
    • Compromissos
    Produtividade
    • Mensagens
    • Aprovações
    • Internet das Coisas
    • VoIP
    • Conhecimento
    • WhatsApp
    Aplicativos de terceiros Odoo Studio Plataforma Odoo Cloud
  • Setores
    Varejo
    • Loja de livros
    • Loja de roupas
    • Loja de móveis
    • Mercearia
    • Loja de ferramentas
    • Loja de brinquedos
    Comida e hospitalidade
    • Bar e Pub
    • Restaurante
    • Fast Food
    • Hospedagem
    • Distribuidor de bebidas
    • Hotel
    Imóveis
    • Imobiliária
    • Escritório de arquitetura
    • Construção
    • Administração de propriedades
    • Jardinagem
    • Associação de proprietários de imóveis
    Consultoria
    • Escritório de Contabilidade
    • Parceiro Odoo
    • Agência de marketing
    • Escritório de advocacia
    • Aquisição de talentos
    • Auditoria e Certificação
    Fabricação
    • Têxtil
    • Metal
    • Móveis
    • Alimentação
    • Cervejaria
    • Presentes corporativos
    Saúde e Boa forma
    • Clube esportivo
    • Loja de óculos
    • Academia
    • Profissionais de bem-estar
    • Farmácia
    • Salão de cabeleireiro
    Comércio
    • Handyman
    • Hardware e Suporte de TI
    • Sistemas de energia solar
    • Sapataria
    • Serviços de limpeza
    • Serviços de climatização
    Outros
    • Organização sem fins lucrativos
    • Agência Ambiental
    • Aluguel de outdoors
    • Fotografia
    • Aluguel de bicicletas
    • Revendedor de software
    Navegar por todos os setores
  • Comunidade
    Aprenda
    • Tutoriais
    • Documentação
    • Certificações
    • Treinamento
    • Blog
    • Podcast
    Empodere a Educação
    • Programa de educação
    • Scale Up! Jogo de Negócios
    • Visite a Odoo
    Obtenha o Software
    • Baixar
    • Comparar edições
    • Releases
    Colaborar
    • Github
    • Fórum
    • Eventos
    • Traduções
    • Torne-se um parceiro
    • Serviços para parceiros
    • Cadastre seu escritório contábil
    Obtenha os serviços
    • Encontre um parceiro
    • Encontre um Contador
    • Conheça um consultor
    • Serviços de Implementação
    • Referências de Clientes
    • Suporte
    • Upgrades
    Github YouTube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Faça uma demonstração
  • Preços
  • Ajuda

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

  • CRM
  • e-Commerce
  • Financeiro
  • Inventário
  • PoS
  • Projeto
  • MRP
All apps
É necessário estar registrado para interagir com a comunidade.
Todas as publicações Pessoas Emblemas
Marcadores (Ver tudo)
odoo accounting v14 pos v15
Sobre este fórum
É necessário estar registrado para interagir com a comunidade.
Todas as publicações Pessoas Emblemas
Marcadores (Ver tudo)
odoo accounting v14 pos v15
Sobre este fórum
Ajuda

OpenERP multiple file upload

Inscrever

Seja notificado quando houver atividade nesta publicação

Esta pergunta foi sinalizada
widgetuploadmultipleimagescontrollers
10 Respostas
22910 Visualizações
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
Cancelar
Avatar
Vicious
Autor Melhor resposta

 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
Cancelar
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
Melhor resposta

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
Cancelar
Avatar
tansadio
Melhor resposta

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
Cancelar
Vicious
Autor

I post a new anwser!

Vicious
Autor

I post a new anwser!

tansadio

Thanks for your answer!

Avatar
yuri
Melhor resposta

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

0
Avatar
Cancelar
Vicious
Autor

i post a new anwser

Está gostando da discussão? Não fique apenas lendo, participe!

Crie uma conta hoje mesmo para aproveitar os recursos exclusivos e interagir com nossa incrível comunidade!

Inscreva-se
Publicações relacionadas Respostas Visualizações Atividade
Is it possible to upload multiple images for main image of the product? Resolvido
product image upload multiple images
Avatar
Avatar
Avatar
Avatar
4
jan. 23
19444
Upload image from website to backend (contact us form)
upload images contactus
Avatar
Avatar
1
nov. 23
8669
I Want to upload multiple files in my module Resolvido
upload multiple odoo odoo13
Avatar
Avatar
1
nov. 21
16636
[Odoo 14] - Model is not updating via Controller
widget models controllers v14
Avatar
Avatar
1
set. 21
5381
Images corrupted after upload
upload debian images odoo10
Avatar
Avatar
3
nov. 17
4899
Comunidade
  • Tutoriais
  • Documentação
  • Fórum
Open Source
  • Baixar
  • Github
  • Runbot
  • Traduções
Serviços
  • Odoo.sh Hosting
  • Suporte
  • Upgrade
  • Desenvolvimentos personalizados
  • Educação
  • Encontre um Contador
  • Encontre um parceiro
  • Torne-se um parceiro
Sobre nós
  • Nossa empresa
  • Ativos da marca
  • Contato
  • Empregos
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Legal • Privacidade
  • Segurança
الْعَرَبيّة 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 é um conjunto de aplicativos de negócios em código aberto que cobre todas as necessidades de sua empresa: CRM, comércio eletrônico, contabilidade, estoque, ponto de venda, gerenciamento de projetos, etc.

A proposta de valor exclusiva Odoo é ser, ao mesmo tempo, muito fácil de usar e totalmente integrado.

Site feito com

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