odoo按钮触发下载文件

时间:2023-03-09 13:25:12
odoo按钮触发下载文件

测试环境:Odoo8.0

1.在你的模块中创建一个方法,返回url

举个例子,

@api.multi

def get_stock_file(self):

return{'type':'ir.actions.act_url',

'url':'/web/binary/download_document?model=wizard.product.stock.report&field=datas&id=%s&filename=product_stock.xls'%(self.id),

'target':'self',}

例中的url包含model及field、id、filename等信息,下一步将在controller方法中抓取到url

2.创建controller类,捕获url,并下载文件

from openerp import http

from openerp.http import request

from openerp.addons.web.controllers.main import serialize_exception,content_disposition

import base64

class Binary(http.Controller):

@http.route('/web/binary/download_document',type='http',auth="public")

@serialize_exception

def download_document(self,model,field,id,filename=None,**kw):

"""Download link for files stored as binary fields.

:param str model:name of the model to fetch the binary from

:param str field:binary field

:param str id:id of the record from which to fetch the binary

:param str filename:field holding the file's name,if any

:returns::class:`werkzeug.wrappers.Response`

"""

Model=request.registry[model]

cr,uid,context=request.cr,request.uid,request.context

fields=[field]

res=Model.read(cr,uid,[int(id)],fields,context)[0]

filecontent=base64.b64decode(res.get(field)or'')

if not filecontent:

return request.not_found()

else:

if not filename:

filename='%s_%s'%(model.replace('.','_'),id)

return request.make_response(filecontent,

[('Content-Type','application/octet-stream'),

('Content-Disposition',content_disposition(filename))])

在上面的方法中从url中拿到ID并返回http响应。

例子中下载的是Excel文件,你可以返回任意类型的文件,甚至是数据库中的二进制字段。