How to cancel form submission when the upload file size exceeds the limit?

I am trying to limit image size using Spring CommonsMultipartResolver . The problem is that the β€œFile Size Exception” is thrown right after the download, but the download continues until the end (due to the nature of POST execution on the form). Thus, I end up saving the temporary file to disk, checking the size and then displaying a verification error message for the user and in addition to spending extra bandwidth / resources.

Is there a way to solve the problem by canceling the form submission when the specified image size is reached?

+4
source share
1 answer

This is only possible by checking it on the client side. You can do this with the new HTML5 File API , which offers a size property that returns the size in bytes. This cannot be achieved in HTML4 (expect perhaps some IE-specific ActiveX features). So you are dependent on the target web browser whether it works. HTML5 is supported in FF> = 3.6, Chrome> = 2 and Safari> = 4 (no, not in IE, not even in IE9!). In any case, you should save the code on the server side to check the file size, and not only as a reserve for browsers that do not support it, but also in cases where enduser disables or hacks the JS code.

Here is an example run:

 <input type="file" onchange="checkSize(this)" /> 

with

 function checkSize(input) { if (input.files && input.files[0].size > (10 * 1024)) { alert("File too large. Max 10KB allowed."); input.value = null; } } 

Yes, input.files is an array. Starting with HTML5, <input type="file"> allows multiple file selection with the multiple attribute.

+2
source

All Articles