Java,MultiPart:确定上传的多部分是否是一种图像

我正在开发一个Spring-MVC应用程序,我有文件上传工具.为此,我想确定用户上传的文件是否是一种图像.

我想创建该图像的缩略图预览,这就是我需要确定它是否是图像的原因.我有缩略图创建代码,没有什么可以知道它是否是一个图像.

请求代码 :

@RequestMapping(value = "/notes/addattachment/{noteid}/{groupaccountid}/{api}", method = RequestMethod.POST)
    public @ResponseBody void addAttachments(@PathVariable("noteid") int noteid, @PathVariable("groupaccountid") Long groupAccountId,
            @PathVariable("api") String api, @RequestParam("attachments") MultipartFile attachment) {
        if (!(attachment.isEmpty())) {
            switch (api){
                case "somecase":
                    try {

                        String fileName = attachment.getOriginalFilename();
                        long fileSize = attachment.getSize();
                        byte[] bytes = attachment.getBytes();
                        this.groupAttachmentsService.addAttachment(bytes, fileName, fileSize, noteid, true,attachment.getContentType());
                        } catch (Exception ignored) {}
                    break;
                case "google":
                    this.driveQuickstart.insertFile(attachment,noteid, groupAccountId,"123");
                    break;
                case "dropbox":
                    String path = api.replace(":","/");
                    this.dropboxTask.insertFile(attachment,"path",noteid, groupAccountId);
                    break;


            }
        }
    }

你能帮忙的话,我会很高兴.谢谢.

解决方法:

如果您正在使用java 7,则可以使用ImageIO来检查文件是否为图像. ImageIO read()
如果未找到图像,则此方法返回null.

上一篇:Failed to parse multipart servlet request; nested exception is java.io.IOException: The temporary up


下一篇:Java将MultipartFile转换为File以获取大文件