如何在网站上获取二进制字段的下载链接



我想从网站上得到一个文件的下载和文件名。

模型
class Files(models.Model):
    _name = 'website_downloads.files'
    name = fields.Char()
    file = fields.Binary('File')

控制器

class website_downloads(http.Controller):
    @http.route('/downloads/', auth='public', website=True)
    def index(self, **kw):
        files = http.request.env['website_downloads.files']
        return http.request.render('website_downloads.index', {
            'files': files.search([]),
        })
模板

<?xml version="1.0" encoding="utf-8"?>
<openerp>
    <data>
        <template id="index" name="Website Downloads Index">
            <t t-call="website.layout">
                <div id="wrap" style="margin-top:50px;margin-bottom:50px">
                    <div class="container text-center">
                        <table class="table table-striped">
                            <t t-foreach="files" t-as="f">
                                <tr>
                                    <td><t t-esc="f.name"/></td>
                                    **<td>Download</td>**
                                </tr>
                            </t>
                        </table>
                    </div>
                </div>
            </t>
        </template>
    </data>
</openerp>

如何获得下载链接,以及在db保存文件时保存原始文件名

Odoo自带内置/web/binary/saveas控制器,可用于此目的:

<t t-foreach="files" t-as="f">
    <tr>
        <td><t t-esc="f.name"/></td>
        <td><a t-attf-href="/web/binary/saveas?model=website_downloads.files&amp;field=file&amp;filename_field=name&amp;id={{ f.id }}">Download</a></td>
    </tr>
</t>

控制器接受四个参数:

  • model—包含Binary字段的模型名称
  • field - Binary字段的名称
  • id -包含特定文件的记录id。
  • filename_field -包含文件名的Char字段的名称(可选)。

最新更新