reset password
Author Message
kknaur
Posts: 540
Posted 21:10 Nov 03, 2010 |

I would like to implement some validation for file upload, mainly checking for the appropriate disk size and whether or not the user has actually chosen a file to upload.  Is there an example in CSNS or some tips on how to write a validator for file uploading?  I realize this isn't required, I am just doing it for my own benefit. 

cysun
Posts: 2935
Posted 07:40 Nov 04, 2010 |

Spring provides two ways to handle an uploaded file (see Slide 13 of the Bits and Pieces lecture notes):

1. The framework can set the file to a String or byte[] property of a command object just like other form fields. If you handle uploaded files this way, you can use a validator to validate the file.

The problem of this approach is that a) it's not suitable for large files, e.g. you don't want to keep a 100MB file in memory as a String or byte[], and b) you lose all other information about the file such as its original name and content type.

2. The second way to handle uploaded files is processing MultipartHttpServletRequest in controller like we do in CSNS. In this case you cannot use a validator to validate because validators only work on command objects. You can however do validation in controller code like the csns.spring.controller.student.UploadFilesController which checks if a file is empty and if the file extension is allowed.

And of course on the client side you can use some JavaScript to validate if the file field is empty before form submission.