Cancel FileUpload when FileSizeMax is exceeded

Deadly 提交于 2020-01-06 07:30:25

问题


I have a JSF application which runs in JBoss 6.1 which uses internal the Tomcat Servlet container.

I've realised the upload with apache commons file upload. I want to prevent too large file uploads and have set the property fileSizeMax to 10MB within the class FileUploadBase. It works, the file upload throws an FileSizeLimitExceededException for all files larger than 10MB. This exception throws within less than a second. But the main problem is, that the whole file will be transferred over the network. I have found this out by checking the network traffic. Afterwards the redirect to the error page is done.

How can I interrupt the file transfer when the max size is exceeded without transferring the whole file? I assume that the file will be transferred in multiple packages because of the web form attribute enctype ="multipart/form-data".


回答1:


You cannot abort a HTTP request halfway. If you did it, you would not be able to return a HTTP response and the client would end up with no form of feedback, expect maybe a browser-specific "Connection reset by peer" error page.

Your best bet is to validate it in JavaScript beforehand. This works by the way only in browsers supporting HTML5 File API. You didn't tell anything about which JSF file upload component you're using, so I have the impression that you just homebrewed one, so I'll give a generic answer which is applicable on the rendered HTML <input type="file"> (note that it works as good on e.g. Tomahawk's <t:inputFileUpload>):

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

with something like this

function checkFileSize(inputFile) {
    var max = 10 * 1024 * 1024; // 10MB

    if (inputFile.files && inputFile.files[0].size > max) {
        alert("File too large."); // Do your thing to handle the error.
        inputFile.value = null; // Clears the field.
    }
}

In case of older browsers not supporting this, well, you're lost. Your best alternative is Flash or Applet.



来源:https://stackoverflow.com/questions/14523632/cancel-fileupload-when-filesizemax-is-exceeded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!