Search code examples
fileodoolimit

How to limit file size in binary field odoo


I have a binary field and I want to limit upload file size to less than 1MB. How can I do that.

binary_field = fields.Binary(string="Upload Image")


Solution

  • The file size of binary fields is limited with max_upload_size which is set to the session max_file_upload_size or to the default value of 128 Mb, it can be changed using the system parameter web.max_file_upload_size

    The max upload size is hard coded and can't be specified from a binary field

    You can extend the existing binary field and set the max file size based on a field attribute.

    Example:

    /** @odoo-module */
    
    import fieldRegistry from 'web.field_registry';
    import basicFields from 'web.basic_fields';
    import session from 'web.session';
    
    
    var CustomFieldBinaryFile = basicFields.FieldBinaryFile.extend({
        init: function (parent, name, record) {
            this._super.apply(this, arguments);
            if(this.attrs.max_upload_size) {
                this.max_upload_size = this.attrs.max_upload_size;
            }
        },
    });
    
    var CustomFieldBinaryImage = basicFields.FieldBinaryImage.extend({
        init: function (parent, name, record) {
            this._super.apply(this, arguments);
            if(this.attrs.max_upload_size) {
                this.max_upload_size = this.attrs.max_upload_size;
            }
        },
    });
    
    fieldRegistry.add('custom_binary', CustomFieldBinaryFile);
    fieldRegistry.add('custom_binary_image', CustomFieldBinaryImage);
    

    Add the js file to the assets entry in the manifest file under web.assets_backend

    To use it set the following attributes on the binary field tag: widget and max_upload_size

    Example:

    <field name="binary_field" widget='custom_binary' max_upload_size="1048576"/>