Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.dineth.shooter.app.view; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * @author dewmal */ @Controller @RequestMapping(value = "/image") public class ImageController { @Autowired private HttpServletRequest request; @Autowired private ApplicationContext context; @Autowired private String homefilefolder; @RequestMapping(value = "/upload", method = RequestMethod.POST) @ResponseBody public String handleFormUpload(@RequestParam("file") MultipartFile file) { File destination = null; if (!file.isEmpty()) { try { BufferedImage src = ImageIO.read(new ByteArrayInputStream(file.getBytes())); destination = new File(homefilefolder + file.getOriginalFilename()); destination.mkdirs(); ImageIO.write(src, FilenameUtils.getExtension(file.getOriginalFilename()), destination); //Save the id you have used to create the file name in the DB. You can retrieve the image in future with the ID. } catch (IOException ex) { Logger.getLogger(ImageController.class.getName()).log(Level.SEVERE, null, ex); } } else { return "bad thing"; } return destination.getName(); } @RequestMapping(value = "/get/{name}.{ext}") public ResponseEntity<byte[]> getImage(@PathVariable("name") String name, @PathVariable("ext") String ext) { Resource resource = context.getResource("file:/home/dewmal/files/" + name + "." + ext); System.out.println(resource.getFilename()); final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.IMAGE_PNG); try { return new ResponseEntity<>(IOUtils.toByteArray(resource.getInputStream()), headers, HttpStatus.CREATED); } catch (IOException ex) { Logger.getLogger(ImageController.class.getName()).log(Level.SEVERE, null, ex); } return null; } }