David Bain
David Bain

Reputation: 2569

Restrict upload by filetype or mimetype using Dexterity on Plone

I have a custom content type, built with dexterity. In the schema (The schema is listed below), I use 'plone.namedfile.field.NamedFile' for attachements/uploads.

I would like to restrict uploads so that only mp3 files can be attached to my content type. What is the best approach for achieving this?

Here is the full schema/model for my content type:

<model xmlns="http://namespaces.plone.org/supermodel/schema">
<schema>
<field name="date" type="zope.schema.Date">
<description />
<title>Date</title>
</field>
<field name="speaker" type="zope.schema.TextLine">
<description />
<title>Speaker</title>
</field>
<field name="service" type="zope.schema.Choice">
<description />
<title>Service</title>
<values>
<element>1st Service</element>
<element>2nd Service</element>
</values>
</field>
<field name="audio_file" type="plone.namedfile.field.NamedFile">
<description />
<title>Audio File</title>
</field>
</schema>
</model>

I shall begin my search here: http://plone.org/products/dexterity/documentation/manual/developer-manual/reference/default-value-validator-adaptors

Upvotes: 4

Views: 494

Answers (1)

David Bain
David Bain

Reputation: 2569

I've decided to use javascript for my first line of validation. I've based my solution on information found at <input type="file"> limit selectable files by extensions

Based on the advice my script looks something like this:

$(document).ready( function() {

function checkFile(event) {
        var fileElement = document.getElementById("form-widgets-audio_file-input");
        var fileExtension = "";
        if (fileElement.value.lastIndexOf(".") > 0) {
            fileExtension = fileElement.value.substring(fileElement.value.lastIndexOf(".") + 1, fileElement.value.length);
        }
        if (fileExtension == "mp3") {
            return true;
        }
        else {
            alert("You must select a mp3 file for upload");
            return false;
        }
    }

$("form#form").bind("submit",checkFile);

});

This is half the solution, next I'll need to add validation on the server side.

Upvotes: 3

Related Questions