Spring MVC File upload tutorial with example



This tutorial shows you how to upload multiple files using Spring MVC Controller


Code

Controller

package com.candidjava.springmvc.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
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.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/uploadFile.htm")
public class FileUploadController {
	private String saveDirectory = "E:/Test/Upload/";

	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView handleFileUpload(HttpServletRequest request,
			@RequestParam CommonsMultipartFile[] fileUpload) throws Exception {

		List<String> list = new ArrayList<String>();

		String desc = request.getParameter("description");
		System.out.println("description: " + desc);

		if (fileUpload != null && fileUpload.length > 0) {
			for (CommonsMultipartFile aFile : fileUpload) {

				System.out.println("Saving file: "
						+ aFile.getOriginalFilename());

				if (!aFile.getOriginalFilename().equals("")) {
					aFile.transferTo(new File(saveDirectory
							+ aFile.getOriginalFilename()));

					// ************************
					list.add(aFile.getOriginalFilename());
					// ************************
				}
			}
		}

		// returns to the view "Result"
		ModelAndView mv = new ModelAndView("Result");
		mv.addObject("description", desc);
		mv.addObject("lists", list);
		mv.addObject("msg", "Succesfully Uploaded..!");

		return mv;
	}
}


Screenshot

            

            


Download

            Spring MVC File upload maven zip

            Spring MVC File Upload war






Comments


©candidjava.com