Home > Java and Web > Spring MVC Single File Upload

Spring MVC Single File Upload

Goal dari post ini adalah men-handle file upload pada aplikasi web Spring MVC.

Langkah 1 : Buat model class / form backing object ( UploadedFile.java )

import org.springframework.web.multipart.MultipartFile;

public class UploadedFile {

private MultipartFile file;

public void setFile(MultipartFile file) {
this.file = file;

public MultipartFile getFile() {
return file;

Langkah 2 : Buat controller class ( UploadController.java )

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.annotation.RequestMapping;

public class UploadController {

UploadValidator uploadValidator;

@RequestMapping(value = "/showFormUpload.do", method = RequestMethod.GET)
public ModelAndView showFormUpload() {
ModelAndView mav = new ModelAndView("SingleFileUploadForm");
return mav;

@RequestMapping(value = "/uploadFile.do", method = RequestMethod.POST)
public ModelAndView uploadedFile(
@ModelAttribute("fileUploaded") UploadedFile uploadedFile,
BindingResult result) {

InputStream inputStream = null;
OutputStream outputStream = null;

MultipartFile file = uploadedFile.getFile();
String fileName = file.getOriginalFilename();

uploadValidator.validate(uploadedFile, result);
if (result.hasErrors()) {
return new ModelAndView("SingleFileUploadForm");
try {
inputStream = file.getInputStream();
File newFile = new File("C:/File Upload/" + fileName);
if (!newFile.exists()) {
outputStream = new FileOutputStream(newFile);
int read = 0;
byte[] bytes = new byte[1024];

while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
} catch (IOException ex) {

return new ModelAndView("FileUploadSuccess", "fileNames", fileName);

Langkah 3 : Buat validator class ( UploadValidator.java )

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.mvc.model.UploadedFile;

public class UploadValidator implements Validator {

public boolean supports(Class clazz) {

return UploadedFile.class.isAssignableFrom(clazz);

public void validate(Object uploadedFile, Errors error) {
UploadedFile file = (UploadedFile) uploadedFile;

if (file.getFile().getSize() == 0) {
error.rejectValue("file", "required");

Buat file message.properties di direktori /WEB-INF/resources  untuk error message di JSP view

required = Select file first.

Buat file Error.css  di folder  di direktori /WEB-INF/css untuk memberi warna text error

.error {
color: #ff0000;

Langkah 4: Buat JSP view form  upload


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<link href="<c:url value="/css/Error.css" />" rel="stylesheet">
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Single File Upload</title>

<form:form method="POST" commandName="fileUploaded" enctype="multipart/form-data" action="uploadFile.do">
Please select a file to upload : <input type="file" name="file" />
<form:errors path="file" cssClass="error"></form:errors>
<input type="submit" value="upload" />


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<h2>Spring MVC file upload example</h2>
FileName below - Uploaded Successful.<br>
<c:forEach items="${fileNames}" var="file">
* ${file} <br>


Langkah 5 : Spring configuration file ( dispatcherServlet-servlet.xml )

<?xml version="1.0" encoding="UTF-8"?>

<beans ... >

<mvc:annotation-driven />
<mvc:resources location="/WEB-INF/" mapping="/**" />
<context:annotation-config />
<context:component-scan base-package="{package to be scanned }"></context:component-scan>

<bean id="viewResolver"
<property name="prefix">
<property name="suffix">

<bean id="multipartResolver"
<property name="maxUploadSize" value="100000" />

<bean id="messageSource"
p:basename="/WEB-INF/resources/messages" />


Screen shoot

File Upload Form

File Upload Form

File Upload Fail

File Upload Fail

File Upload Success

File Upload Success

Referensi : dari berbagai sumber.

Semoga bermanfaat

  1. No comments yet.
  1. No trackbacks yet.

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

%d bloggers like this: