Check file size before ColdFusion upload

I found a neat little way of checking a file size before full upload in CF by using Java io. In Java the following "file.length();" will get the number of bytes in the file. In CF you can do this...

view plain print about
1createObject("java","java.io.File").init("image.png").length()

So something like this is neat and tidy.

view plain print about
1if (createObject("java","java.io.File").init("image.png").length() gt xx)
2 return false;
3 else
4 fileUpload("D:\","#arguments.image#","","makeUnique");

There are of course many other ways of doing this, but simple things like this impress me.

Sep19

Comments 5

  1. andy matthews's Gravatar # Posted By andy matthews
    19/09/11 15:09

    How can Java on the server get the file size of a file on the user's machine?

  1. Russ Johnson's Gravatar # Posted By Russ Johnson
    19/09/11 15:11

    This wouldn't check the file size "before" the file was uploaded would it? The file would have to be uploaded to the server before Java would be able to get the size of the file.

  1. Jeff Smallwood's Gravatar # Posted By Jeff Smallwood
    19/09/11 16:27

    Glyn, not sure I understand how this helps CF see the size before upload. In the code example the init accepts a file reference, but that file reference wouldn't exist on the CF server until AFTER the file had already been uploaded...unless I'm missing something.

  1. Azadi Saryev's Gravatar # Posted By Azadi Saryev
    19/09/11 16:31

    When you say "before upload", you do not mean 'on client macine', do you? Just before the cffile action="upload' runs (after the form is submitted and the file is POSTed to server).

  1. Glyn Jackson's Gravatar # Posted By Glyn Jackson
    19/09/11 17:49

    Yes maybe I need to explain better. Normally you would have to FULLY upload the image. Of course, it still has to leave the clients machine first, there is not way you could read the size of the file on the clients machine I know of. With the method above it just creates a Java object, gets the size of the file in bytes. Meaning you don’t have to upload fully then delete if too big as in the case with cffile upload.

    I have edited the post and title (sorry). I have also added an example of how I use it. With this method I don't need to clean up the object, or in the case of cffile, delete it after.

    I think it's just a little more tidy.