我在 odoo 中有一个自定义 Web 表单。我需要上传文件。我的 Controller .py:
@http.route(['/test/'], type='http', auth="user", methods=['GET', 'POST'], website=True)
def upload_files(self, **post):
values = {}
form_vals = {}
...........
if post.get('attachment',False):
Attachments = request.registry['ir.attachment']
name = post.get('attachment').filename
file = post.get('attachment')
attachment_id = Attachments.create(request.cr, request.uid, {
'name':name,
'res_name': name,
'type': 'binary',
'res_model': 'project.issue',
'res_id': form_id,
'datas': base64.encode(file.read()),
}, request.context)
............
上面的代码创建了附件,名称为 res_model 等,但是附件文件已损坏,无法打开。
XML 文件:
..........
<form t-attf-action="/test/done" method="post" enctype="multipart/form-data" class="form-horizontal mt32"><div t-attf-class="form-group">
..........
<div t-attf-class="form-group">
<label class="col-md-3 col-sm-4 control-label" for="attachment">Attachments</label>
<div class="col-md-7 col-sm-8">
<input name="attachment" type="file" class="file" multiple="true" data-show-upload="true" data-show-caption="true" lass="file" data-show-preview="true"/>
</div>
</div>>
..........
</form>
在控制台中:
name = post.get('attachments_for_issue').filename
_logger.error("name is: %r", name)
file = post.get('attachments_for_issue')
_logger.error("file is?: %r", file.read())
返回:
5092 ERROR HDHDHD openerp.addons.test.controllers.controllers: name is: u'test_image.jpg'
5092 ERROR HDHDHD openerp.addons.test.controllers.controllers: file is?: <FileStorage: u'test_image.jpg' ('image/jpeg')>
最佳答案
我认为问题出在 base64.encode(file.read())
从 python 文档我们有
base64.encode(输入,输出)¶
对输入文件的内容进行编码,并将生成的 base64 编码数据写入输出文件。输入和输出必须是文件对象或模仿文件对象接口(interface)的对象。输入将被读取,直到 input.read() 返回一个空字符串。 encode() 返回编码数据加上尾随的换行符('\n')。
所以,尝试这样使用并检查
附件 = file.read()
然后
'数据':附件.encode('base64')
关于python - 在 Odoo 网络表单中上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31906671/