简体   繁体   中英

Can I specify a file type in GWT FileUpload?

I have a Gwt application and use a FileUpload to allow users to upload files. Only certain types of files will be accepted and I have validation to check the file types once the user has selected it for uploading but I want to know if there is a way to only show files with certain extensions in the upload dialog box.

Eg If the user has to upload a .doc file then I only want them to be able to see folders and .doc's, not All file types.

Using Zasz's answer and GWT Element it is possible to have an initial filter applied to the dialog box although it's not bulletproof...

myFileUpload.getElement().setAttribute("accept", ".txt");

At least this worked for me in a learning project . 'accept' has other formats too.

The nearest I can come up with is using this

<input type="file" accept="image/jpg,image/gif">

together with :

<form action="pat/to/action" enctype="multipart/form-data" method="post">

though it does no validations or makes any any changes to the open file dialog itself. A better option will be to let the user select whatever file and when onClick() use a javascript function to check extension, and a neat little square area below the file upload control that gives the user feedback about the validity of the file he selected.

As per my knowledge

There is no programmatical way to only show files with certain extensions in the upload dialog box.

You need to put validations on selected file

You can create a comma separated string of mime types you want to support (below one is for xls, xlsx etc )

String mimeList = "application/vnd.ms-excel,application/msexcel,application/"
        + "x-msexcel,application/x-ms-excel,application/vnd.ms-excel,application/"
        + "x-excel,application/x-dos_ms_excel,application/xls,application/"
        + "vnd.openxmlformats-officedocument.spreadsheetml.sheet";

myFileUploader.setAcceptedTypes(mimeList);

Please note that there's no guarantee that this will work in all browsers.

I have tested with Google chrome only and it works!

The W3C spec says only that this "provides the user agent with a hint of file types to accept". How it does that is up to the browser, and the browser is free to give the user the option to select any file, notwithstanding your list of acceptable MIME types. So you're still going to want to validate the file when the user clicks the submit button or at the server side.

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