如何在Wicket,FileUploadField中设置文件扩展名?

时间:2013-11-27 09:11:01

标签: java file-upload wicket file-extension

我有一个FileUploadField组件,我想只上传*.css*.html个文件。但现在,我可以上传任何类型的文件。我怎样才能将文件的扩展名设置为该组件?我的代码和平:

FileUploadField ret = new FileUploadField("uploadField");
ret.setRequired(true);
form.add(fileUploadField);

谢谢!

4 个答案:

答案 0 :(得分:7)

请注意,accept仅适用于现代浏览器(Documentation),您也可以在服务器端进行检查。

可能的解决方案:

FileUploadField ret = new FileUploadField("uploadField") {
    @Override
    protected void onComponentTag(ComponentTag tag)
    {
        // Default handling for component tag
        super.onComponentTag(tag);

        tag.put("accept", ".css,.html");        
    }

    @Override
    public List<FileUpload> getFileUploads() {
        return filter(super.getFileUploads());
    }

    private List<FileUpload> filter(List<FileUpload> fileUploads) {
        // filter out all files with invalid extension 
    }
};

答案 1 :(得分:4)

我必须在html文件中设置它,而不是在java文件中设置它:

<input type="file" wicket:id="uploadField" accept=".csv, .html"/>

答案 2 :(得分:3)

您可以创建一个扩展AbstractValidator的FileExtensionValidator并将其添加到您的上传字段。

public class FileExtensionValidator extends AbstractValidator
{
  private final List<String> allowedFileTypes = Arrays.asList("HTML","CSV");

  public void onValidate(IValidatable _validatable)
  {
    List files = (ArrayList) _validatable.getValue();
    for (Object o : files)
    {
      FileUpload file;
      file = FileUpload.class.cast(o);
      String fileName = file.getClientFileName();
      String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);
      if (!allowedFileTypes.contains(fileExt.toUpperCase()))
      {
        ValidationError error = new ValidationError();
        error.addMessageKey("UnsupportedExtension");
        error.setVariable("ValidExtensions", allowedFileTypes.toString());
        _validatable.error(error);
      }
    }
  }
}

答案 3 :(得分:1)

使用新文件()

File newFile = new File("yourPath", "yourFilename.css");
newFile.createNewFile();
yourUpload.writeTo(newFile);

就是这样!