开发者

client side file size validation javascript

开发者 https://www.devze.com 2023-03-13 20:30 出处:网络
Whenever I am selecting a file of size more than 50MB to upload, my JBoss server is throwing an exception and JSP is hanging. So, instead of validating the file size at java server side, I have to val

Whenever I am selecting a file of size more than 50MB to upload, my JBoss server is throwing an exception and JSP is hanging. So, instead of validating the file size at java server side, I have to validate it at client side. But I cannot find any proper approach on that. Can anybody help me on 开发者_StackOverflow中文版that? I can't use any flash upload feature.


You don't want to use client side validation for this. Not only JS cannot access the file metadata anyway, but JS can also be turned off or even fully spoofed.

As to the concrete problem, it sounds much like as if you're parsing the uploaded file inside a JSP file instead of a normal Java (Servlet) class. Because JSP is as being a view technology part of the HTTP response, any exception which is been thrown halfway JSP's output, the server cannot change the HTTP response into an error page anymore. The client will most likely end up with a blank page with a halfbaked HTML source because the JSP output was abruptly been aborted.

To fix this, you should be avoiding Java code in JSP files and put Java code in normal Java classes instead. In this particular case, you want to use a servlet. Let the form submit to a servlet instead of a JSP.

<form action="uploadServlet" method="post">

Here's a kickoff example of how its doPost() method should look like:

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        // Parse file upload.

        // At end, forward request/response to JSP to present results in HTML.
        request.getRequestDispatcher("/WEB-INF/results.jsp").forward(request, response);
    } catch (FileUploadException e) { // Or whatever exception it is throwing.
        throw new ServletException("File upload failed", e);
    }
}

This way the exception will end up in a default HTTP 500 error page which you can customize as follows in web.xml anyway

<error-page>
    <exception-type>com.something.FileUploadException</exception-type>
    <location>/someFileUploadErrorPage.jsp</location>
</error-page>

Alternatively, instead of throwing ServletException, you can also just set the error message as an attribute and forward to same JSP and let it display the error in an user friendly manner in the same form. You can get the general idea in our servlet wiki page.

0

精彩评论

暂无评论...
验证码 换一张
取 消