简体   繁体   中英

Check file size before upload using GWT

I'm using a FormPanel to upload a file to a server. What I'm trying to do is make sure the file size is smaller than a given size (eg 10MB) before uploading it. On the server side I have a javax.servlet.http.HttpServlet where I'm overriding doPost. Here the HttpServletRequest parameter has the size of the file, but the problem is I don't reach doPost until the file has already been uploaded. So if I chose to upload a 1 GB file, the "File too large" error message the client receives doesn't show up for 30 seconds or so, after the entire file has been uploaded.

Isn't there any way to check the size on the client side, before it's uploaded? Alternatively, get the servlet to throw an exception if the size of the data exceeds the specific size.

Just add native method:

private native int getFileSize(final Element data) /*-{
            return data.files[0].size;
        }-*/;

And then call it like this:

final FileUpload upload = new FileUpload();
//
// some actions
//
final int size = getFileSize(upload.getElement())

Works fine as for me.

There isn't a way to do it from the server, you have to do the check before you do the upload. There are several routes you could take none of which you're going to find in the GWT SDK.

Because not all of the browsers supported by GWT implement HTML5's File API there isn't a native GWT solution. You can however try this library which gives you file upload widgets that support the HTML5 file api:

https://code.google.com/p/lib-gwt-file/

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