Site icon

Multipart file upload RESTFul web service (Spring MVC/ java/ example)

File upload is very common scenario in today’s web application. In this post, We will discuss about RESTFul web service exposing Multipart file upload resource using spring mvc.

Multipart REST Service (“multipart/mixed”  mime):

Spring Multipart file upload service capable of consuming different kind of files like pdf, txt, json, zip etc. In Multipart project we will have HomeController resource capable of accepting the different kind of files format. We need to create the Spring MVC application, which will have standard spring configuration. we can use maven or spring template to create sample spring application. We can able to download the complete project from the link specified at the bottom of page.
We have discussed about the multipart file upload client, we can use file upload client to upload different files formats like jpg, pdf, json and zip file.

1. Controller containing multi part REST resource:

 Once we have default spring MVC application created where in, we will have Controller resource module.We perform following changes to make it capable of consuming multipart file upload request coming from client.Multipart Server will have “handleFileUpload” which will expose REST post api. Also, it is consuming “multipart/mixed”, which means it is capable of consuming multipart contents. This API is capable of accepting different kinds of files like pdf, json, zip, image etc. File upload client can upload any kind of file it wants to upload to this service.Let us have a look into the complete controller resource, which will be invoked by REST client.

package org.learn.repo;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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 org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/file")
public class HomeController {
	
	//private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		//logger.info("Welcome home! The client locale is {}.", locale);		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);		
		String formattedDate = dateFormat.format(date);		
		model.addAttribute("serverTime", formattedDate );		
		return "home";
	}
	
	@RequestMapping(value="/upload", method=RequestMethod.POST, consumes = {"multipart/mixed"})
    public @ResponseBody String handleFileUpload(
    		@RequestParam(value = "textMessage",required=false) String message,
            @RequestParam(value = "pdfFile", required = false) MultipartFile pdfFile,
            @RequestParam(value = "jsonFile", required = false) MultipartFile jsonFile, 
            @RequestParam(value = "zipFile", required = false) MultipartFile zipFile, 
            @RequestParam(value = "imgFile", required = false) MultipartFile imageFile,            
            MultipartHttpServletRequest request, ModelAndView modelAndView){    
		
		//We have specified the individual file. We can proceed ahead to use if required
		//Here we are extracting the file names from request parameters
		List<String> requestKeys = new ArrayList<String>();
		List<String> originalFiltName = new ArrayList<String>();
		request.getFileNames().forEachRemaining(requestKeys::add);		
		for(String multiPartFile : requestKeys) {
			originalFileName.add(request.getFile(multiPartFile).getOriginalFilename());
		}
		return "uploaded files :" + originalFileName.toString();
		//for web clients
		//modelAndView.addObject("files", uploadedFileList);
		//return "FileUpload";
    }
}

2. Spring Configuration (MultipartResolver):

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/root-context.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>

We can have a look into the complete code (Multipart Server ). Refer ReadMe.md file under project directory for more details. In our POM we have included the most of dependencies which are required to build web application using spring framework.

Download Code – Spring MVC multipart file server

 

Exit mobile version