Filedocument filesize

1
We need to show the filesize of a filedocument in a grid. Anyone with some ideas?
asked
3 answers
2

You can't know the size of an inputstream without reading it as far as I know, so I would just read the inputstream of each filedocument, maybe as an after-commit action, and count the number of bytes you're reading. You can save this number by inheriting from FileDocument and using those entities, or making an entity associated with FileDocument.

answered
4

The java, as available in the community commons module to do this. Note that the method uses two different implementations to determine the filesize. (The first one is faster, but requires java to have access rights on the files on disk)

public static Long getFileSize(IContext context, IMendixObject document)
{
    long size = 0;
    if (context != null) {
        try {
            try {
                File f = Core.getFileDocumentContentAsFile(context, document);
                size =  f.length();
            }
            catch (AccessControlException e1) {
                    //We seem to be in cloud security mode..., naive implementation: read the whole stream, count the bytes
                    InputStream in = Core.getFileDocumentContent(context, document);
                    byte[] buffer = new byte[1024];
                    int i;
                    while ((i = in.read(buffer)) != -1) 
                        size += i;
            }
        }
        catch(Exception e) {
            throw new RuntimeException("Unable to read filesize: " + e.getMessage(), e);
        }
    }
    return size;
}
answered
3

You can store the file size in an attribute of the entity that specializes FileDocument. In the after-commit event you can update this attribute using a tiny bit of Java code.

answered