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;

@Controller
public class UploadController {

@Autowired
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()) {
newFile.createNewFile();
}
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) {
ex.printStackTrace();
}

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;

@Component
public class UploadValidator implements Validator {

@Override
public boolean supports(Class clazz) {

return UploadedFile.class.isAssignableFrom(clazz);
}

@Override
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

SingleFileUploadForm.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Single File Upload</title>

</head>
<body>
<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>
<br>
<input type="submit" value="upload" />
</form:form>
</body>
</html>

FileUploadSuccess.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>Spring MVC file upload example</h2>
FileName below - Uploaded Successful.<br>
<c:forEach items="${fileNames}" var="file">
* ${file} <br>
</c:forEach>

</body>
</html>

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"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>

<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="100000" />
</bean>

<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
p:basename="/WEB-INF/resources/messages" />

</beans>

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: