简体   繁体   中英

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

I'm trying to limit the image size using Spring CommonsMultipartResolver . The problem is that the "File size exception" gets thrown immediately upon upload but the upload continues to the end (due to the nature of doing a POST on a form). So, I end up saving a temp file on the disk, checking the size and then displaying validation error message to the user and on top of that wasting additional bandwidth / resources.

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

This is only possible by checking it in the client side. You can do it with the new HTML5 File API which offers a size property which returns the size in bytes. There is no way to achieve this in HTML4 (expect of possibly some IE-specific ActiveX functions) You're thus dependent on the target webbrowser whether it works. HTML5 is supported in FF >= 3.6, Chrome >= 2 and Safari >= 4 (no, not in IE, even not IE9 yet!). You should in any case keep your server side code to check the file size, not only as fallback for browsers not supporting it, but also for cases where the enduser disables or hacks the JS code.

Here's a kickoff example:

<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, the input.files is an array. Since HTML5 the <input type="file"> allows multiple file selection by multiple attribute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM