Can I specify a file type in GWT FileUpload?

别等时光非礼了梦想. 提交于 2019-12-24 16:35:28

问题


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.

E.g. 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.


回答1:


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




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/5376266/can-i-specify-a-file-type-in-gwt-fileupload

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