odoo表单相关的附件文档如果过多,逐个下载到本地也是一种负担,比较好的方式是提供一种打包下载的可选功能,既可以提高操作效率也可以减少网络下载流量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
''' author: i@renjie.me ''' class Binary(http.Controller): @http.route('/web/binary/download_attachment', type='http', auth='user') def download_attachment(self, model, id): attachment_model = request.env['ir.attachment'] attachment_ids = attachment_model.search([('res_model', '=', model), ('res_id', '=', id)]) file_dict = {} for attachment_id in attachment_ids: file_store = attachment_id.store_fname #文件附件 if file_store: file_name = attachment_id.name file_path = attachment_id._full_path(file_store) file_dict["%s:%s" % (file_store, file_name)] = dict(path=file_path, name=file_name) _logger.info("download attachment ready : %s" % file_dict) #压缩包名 record_value = request.env[model].search_read(domain=[('id', '=', id)], fields=['name']) zip_filename = "attachment" if len(record_value) == 1: record_name = record_value[0].get("name", "") if record_name: zip_filename = record_name zip_filename = "%s.zip" % zip_filename #内存压缩 strIO = StringIO.StringIO() zip_file = zipfile.ZipFile(strIO, "w", zipfile.ZIP_DEFLATED) for file_info in file_dict.itervalues(): zip_file.write(file_info["path"], file_info["name"]) zip_file.close() _logger.info("download attachment pack : %s(%s)" % (zip_filename, strIO.len)) #二进制 return request.make_response(strIO.getvalue(), headers=[('Content-Type', 'application/x-zip-compressed'), ('Content-Disposition', content_disposition(zip_filename))]) |
打包下载路径举例:
http://renjie.me/web/binary/download_attachment?model=project.task&id=1983