Search code examples
javaimage-uploadingmultipart

Java, MultiPart : Determine if multipart uploaded is a type of image


I am working on a Spring-MVC application in which I have file-upload facility. For this, I would like to determine if the file which is uploaded by the user is a type of image.

I would like to create a thumbnail preview of that image, that is why I need to determine if it's an image. I have the thumbnail creation code with me, just nothing to know if it's an image.

Request code :

@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;


            }
        }
    }

Any help would be nice. Thank you.


Solution

  • If you're using java 7 ImageIO is the class you can use to check if file is image or not. ImageIO read() This method returns null if no image found.