Spring MultipartFile file upload example


      Click here to attend Spring Framework 4.x and certification course with a discount

package nl.kameroom.controller;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.FileImageOutputStream;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.coobird.thumbnailator.Thumbnails;
import nl.kameroom.image.ImageService;
import nl.kameroom.user.UserManager;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import sun.java2d.pipe.BufferedBufImgOps;

@Controller
public class FileUploadController {

	@Value("#{settings['upload.profile.thumb.loc']}")  
	private String profileThumbPath= "";
	 
	@Value("#{settings['upload.profile.org.loc']}")  
	private String profileOrgPath= "";
	
	@Value("#{settings['upload.advert.thumb.loc']}")  
	private String advertThumbPath= "";
	
	@Value("#{settings['upload.advert.org.loc']}")  
	private String advertOrgPath= "";

	private UserManager userManager;
	private ImageService imageService;

	@Autowired
	public void setUserManager(UserManager um) {
		userManager = um;
	}
	
	@Autowired
	public void setImageService(ImageService is) {
		imageService = is;
	}

    @RequestMapping(value = "/profile/photoupload.k", method = RequestMethod.POST)
    public @ResponseBody ResponseEntity<String> profilePhotoUpload(@RequestParam("photo") MultipartFile file,
    		ModelMap model, 
    		HttpServletRequest request, 
    		HttpServletResponse response,
    		Authentication auth) {
    	
    	String orgName = "";
    	String r = "";
    	int idUser = 0;
        if (!file.isEmpty()) {
          try {
    	   	
    	    byte[] bytes = file.getBytes();					
            orgName = "p" + "." + file.getOriginalFilename().substring(file.getOriginalFilename().indexOf(".")+1);
            r = imageService.validateFile(file.getContentType(),file.getName(), file.getOriginalFilename(), file.getSize());
            if(r.equals("")) {

            idUser = userManager.getUserIDByUsername(auth.getName());
            File dest = new File(profileOrgPath + idUser + "/");
            File destFile = new File(profileOrgPath + idUser + "/" + orgName);
            
            if(!dest.exists()) {
            	dest.mkdir();             	
            } else {
            	//remove all files
            	File[] inDir = dest.listFiles();
            	for (int i = 0; i < inDir.length; i++) {
					inDir[i].delete();					
				}
            }
            
            BufferedImage img = ImageIO.read(file.getInputStream());
            //file.transferTo(destFile);   
            imageService.compressAndWriteImage(img, destFile);
            
            //profile thumb photo            
            File outFile = new File(profileThumbPath + idUser +"/");
            if(!outFile.exists()) {
            	outFile.mkdir(); 
            }
            else
            {	//remove all files
            	File[] inDir = outFile.listFiles();
            	for (int i = 0; i < inDir.length; i++) {
					inDir[i].delete();					
				}
            }
            
            Thumbnails.of(img).forceSize(112, 81).toFile(outFile + "/" + orgName);
            //profile thumb photo
            userManager.setUserProfilePath(idUser, orgName);
			} 
            } catch (Exception e) {
            	//LOGGING
                e.printStackTrace();
            }
            
            String json= "";
          	if(r.equals(""))
          		json = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><p><n>"+orgName+"</n><l>/uploads/thumbnail/profile/"+ idUser + "/" + orgName+"</l></p>";
          	else
          		json = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><p><e>" + r + "</e></p>";
          	HttpHeaders responseHeaders = new HttpHeaders();
            responseHeaders.setContentType(MediaType.TEXT_XML);
            return new ResponseEntity<String>(json, responseHeaders, HttpStatus.OK);

       } else {
    	   return  null;
       }      
    }

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s