如何使用Annotation在SpringMVC中的模型中验证mime类型的图像?

时间:2016-04-18 08:59:51

标签: java spring spring-mvc bytearray mime-types

我在我的应用程序中有这个模型,我上传了一个image / svg + xml到我的服务器:

public class ImageModel{

    private Integer Id;

    @NotEmpty
    @Pattern(regexp = "^[a-zA-Z0-9äöüÄÖÜ\\d\\-_\\s]+$")
    private String name;

    //here some annotation to check the mimetype of this byte array
    private byte[] data;
 }

有没有办法验证字段数据的mime类型,这里直接在带有注释的模型中?

1 个答案:

答案 0 :(得分:0)

我找不到Model @Annotations的解决方案,我通过在我的控制器中进行验证检查来解决它:

     InputStream is = new BufferedInputStream(new ByteArrayInputStream(myByteArray));
            String mimeType = URLConnection.guessContentTypeFromStream(is);

            if ( mimeType == null){
                result.addError(new ObjectError("file", "Only SVG allowed!"));
            }else if(mimeType != null && !mimeType.equalsIgnoreCase("application/xml")){
                result.addError(new ObjectError("file", "Sorry Bro, only SVG allowed!"));
            }
 if (result.hasErrors()) {
            // send back to edit form
            model.addAttribute("uploadForm", data);
            return "image/editPage";
        }