Useful to check any uploaded files are of the correct file type and matches the file extension. e.g. to stop someone renaming an executable file as a .jpg
Code: Select all
package com.ebasetech.ufs.customfunctions;
import java.util.*;
import org.nfunk.jep.*;
import com.ebasetech.ufs.function.*;
import com.ebasetech.ufs.kernel.*;
import java.io.File;
import org.apache.tika.Tika;
import org.apache.tika.detect.DefaultDetector;
import org.apache.tika.detect.Detector;
import org.apache.tika.io.TikaInputStream;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.mime.MimeTypes;
public class GetFileMimeType extends UFSCustomFunction {
public GetFileMimeType (UFSFormInterface formInterface) {
super(formInterface);
/* Specify the number of parameters to be received by the custom function */
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
boolean fileExists = false;
String mimeType = null;
Object param1 = inStack.pop();
if ( param1 instanceof String ) {
String fileName = param1.toString();
if ( fileName.length() == 0) {
inStack.push(new String("ERROR"));
return;
}
try {
fileExists = (new File(fileName)).exists();
if ( fileExists ) {
File f = new File(fileName);
Tika tika = null;
TikaInputStream is = null;
// Creating new Instance of org.apache.tika.Tika
tika = new Tika();
// Detecting MIME Type of the File
mimeType = tika.detect(f);
inStack.push(new String(mimeType));
return;
} else {
inStack.push(new String("NOFILE"));
return;
}
} catch ( Exception e ) {
inStack.push(new String("ERROR"));
return;
}
} else {
inStack.push(new String("ERROR"));
return;
}
}
}