SCENARIO: We want to restrict the user to upload a file whose extension is .exe and whose size is more than 5 MB.
IMPLEMENTATION: To check the file extension, write a filter on postValidateCheckinData event. To check the file size, write a filter on validateStandard event.
postValidateCheckinData
Executed at the end of the action validateCheckinData and after the filter validateCheckinData. This is a good place for last-minute alterations of the metadata prior to a check-in.
validateStandard
Executed during update or check-in. This runs before the core validates the metadata fields, such as dReleaseState, dDocName, dRevClassID, dDocTitle, primaryFile, alternateFile, dCreateDate, dInDate, and dOutDate.
IMPLEMENTATION: To check the file extension, write a filter on postValidateCheckinData event. To check the file size, write a filter on validateStandard event.
postValidateCheckinData
Executed at the end of the action validateCheckinData and after the filter validateCheckinData. This is a good place for last-minute alterations of the metadata prior to a check-in.
validateStandard
Executed during update or check-in. This runs before the core validates the metadata fields, such as dReleaseState, dDocName, dRevClassID, dDocTitle, primaryFile, alternateFile, dCreateDate, dInDate, and dOutDate.
private void checkFileExtension(DataBinder binder) throws ServiceException {
String dExtension = binder.getLocal("dExtension");
trace("dExtension: " + dExtension);
String ExtensionsToControl = "";
if (SharedObjects.getEnvironmentValue("ExtensionsToControl") != null) {
ExtensionsToControl = SharedObjects.getEnvironmentValue("ExtensionsToControl");
}
trace("ExtensionsToControl: " + ExtensionsToControl);
if (ExtensionsToControl.indexOf(dExtension) >= 0) {
String msg = LocaleUtils.encodeMessage("csExtensionsToControl", null, dExtension);
throw new ServiceException(msg);
}
}
private void checkFileSize(DataBinder binder) throws ServiceException {
//trace(binder.m_tempFiles.toString());
String primaryFilePath = binder.getLocal("primaryFile:path");
trace("primaryFilePath: " + primaryFilePath);
File file = new File(primaryFilePath);
long fileSize = file.length();
trace("fileSize: " + fileSize);
if (fileSize >= 5 * 1024 * 1024) {
throw new ServiceException("This document is too large.");
}
}
Create an environment file as well:
ExtensionsToControl=exe,rar
I had also created a string resource file to display the error message in case the file extension matches with the one provided in the environment file:
<@csExtensionsToControl=Files of extension {1} cannot be uploaded.@>
NOTES
1. A better approach is provided in the link below:
http://sonaloraclewebcenter.blogspot.in/2015/04/ucm-validating-file-extension.html
2. If you want to check the mime type of the file and not the extension, use Apache Tika 1.7.