Spring MVC File Upload Example Tutorial – Single and Multiple Files

来源:互联网 发布:网络卖电影挣钱 编辑:程序博客网 时间:2024/05/20 18:00

File Uploading is a very common task in any web application. We have earlier seen how to upload files in Servlet and Struts2 File Uploading. Today we will learn about Spring File upload, specifically Spring MVC File Upload for single and multiple files.

Spring MVC framework provide support for uploading files by integrating Apache Commons FileUpload API. The process to upload files is very easy and requires simple configurations. We will create a simple Spring MVC project in STS that will look like below image.


Most of the part is the boiler-plate code generated by STS tool, we will focus into the changes that are required to utilize Spring file upload integration.

upload.jsp view code:

<%@ 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>Upload File Request Page</title></head><body><form method="POST" action="uploadFile" enctype="multipart/form-data">File to upload: <input type="file" name="file">Name: <input type="text" name="name"><input type="submit" value="Upload"> Press here to upload the file!</form></body></html>
uploadMultiple.jsp view code:
<%@ 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" %><%@ page session="false" %><!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>Upload Multiple File Request Page</title></head><body><form method="POST" action="uploadMultipleFile" enctype="multipart/form-data">File1 to upload: <input type="file" name="file">Name1: <input type="text" name="name">File2 to upload: <input type="file" name="file">Name2: <input type="text" name="name"><input type="submit" value="Upload"> Press here to upload the file!</form></body></html>

Notice that these files are simple HTML files, I am not using any JSP or Spring tags to avoid complexity. The important point to note is that form enctype should be multipart/form-data, so that Spring web application knows that the request contains file data that needs to be processed.

Also note that for multiple files, the form field “file” and “name” are same in the input fields, so that the data will be sent in the form of array. We will take the input array and parse the file data and store it in the given file name.

Spring MVC Multipart Configuration

To utilize Apache Commons FileUpload for handling multipart requests, all we need to do is configuremultipartResolver bean with class as org.springframework.web.multipart.commons.CommonsMultipartResolver.

Our final Spring configuration file looks like below.

springmvc-web.xml code:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context     http://www.springframework.org/schema/context/spring-context-3.0.xsd     http://www.springframework.org/schema/mvc     http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"><context:component-scan base-package="com.npf.controller"/><mvc:annotation-driven /><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><property name="maxUploadSize" value="100000" /></bean><mvc:resources location="/resources/" mapping="/resources/**"/><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property><property name="prefix" value="/WEB-INF/jsp/"/><property name="suffix" value=".jsp"/></bean></beans>
Notice that I am setting maximum upload size limit by providing the maxUploadSize property value formultipartResolver bean. If you will look into the source code of DispatcherServlet class, you will see that a MultipartResolver variable with name multipartResolver is defined and initialized in below method.

private void initMultipartResolver(ApplicationContext context)  {    try    {      this.multipartResolver = ((MultipartResolver)context.getBean("multipartResolver", MultipartResolver.class));      if (this.logger.isDebugEnabled()) {        this.logger.debug("Using MultipartResolver [" + this.multipartResolver + "]");      }    }    catch (NoSuchBeanDefinitionException ex)    {      this.multipartResolver = null;      if (this.logger.isDebugEnabled())        this.logger.debug("Unable to locate MultipartResolver with name 'multipartResolver': no multipart request handling provided");    }  }
With this configuration, any request with enctype as multipart/form-data will be handled by multipartResolver before passing on to the Controller class.

Spring File Upload Controller Class

Controller class code is very simple, we need to define handler methods for the uploadFile anduploadMultipleFile URIs.

FileUploadController.java code:

package com.npf.controller;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileOutputStream;import org.slf4j.Logger;import org.slf4j.LoggerFactory;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.bind.annotation.ResponseBody;import org.springframework.web.multipart.MultipartFile;/** * Handles requests for the application file upload requests */@Controllerpublic class FileUploadController {private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class);/** * Upload single file using Spring Controller */@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)public @ResponseBody String uploadFileHandler(@RequestParam("name") String name,@RequestParam("file") MultipartFile file) {if (!file.isEmpty()) {try {byte[] bytes = file.getBytes();// Creating the directory to store fileString rootPath = System.getProperty("catalina.home");File dir = new File(rootPath + File.separator + "tmpFiles");if (!dir.exists()){dir.mkdirs();}// Create the file on serverFile serverFile = new File(dir.getAbsolutePath() + File.separator + name);BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));stream.write(bytes);stream.close();logger.info("Server File Location= " + serverFile.getAbsolutePath());return "You successfully uploaded file= " + name;} catch (Exception e) {return "You failed to upload " + name + " => " + e.getMessage();}} else {return "You failed to upload " + name + " because the file was empty.";}}/** * Upload multiple file using Spring Controller */@RequestMapping(value = "/uploadMultipleFile", method = RequestMethod.POST)public @ResponseBody String uploadMultipleFileHandler(@RequestParam("name") String[] names,@RequestParam("file") MultipartFile[] files) {if (files.length != names.length){return "Mandatory information missing";}String message = "";for (int i = 0; i < files.length; i++) {MultipartFile file = files[i];String name = names[i];try {byte[] bytes = file.getBytes();// Creating the directory to store fileString rootPath = System.getProperty("catalina.home");File dir = new File(rootPath + File.separator + "tmpFiles");if (!dir.exists()){dir.mkdirs();}// Create the file on serverFile serverFile = new File(dir.getAbsolutePath() + File.separator + name);BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));stream.write(bytes);stream.close();logger.info("Server File Location= " + serverFile.getAbsolutePath());message = message + "You successfully uploaded file=" + name;} catch (Exception e) {return "You failed to upload " + name + " => " + e.getMessage();}}return message;}@RequestMapping(value="/upload",method = RequestMethod.GET)public String toUploadFilePage(){return "upload";}@RequestMapping(value="/uploadMultiple",method = RequestMethod.GET)public String toUploadMultipleFilePage(){return "uploadMultiple";}}
Notice the use of Spring annotations that make our life easier and code looks more readable.

uploadFileHandler method is used to handle single file upload scenario whereas uploadMultipleFileHandlermethod is used to handle multiple files upload scenario. Actually we could have a single method to handle both the scenarios.
When we run our application, below images shows us the request and responses.

Spring MVC File Upload Example


You can check the server logs to know the location where the files have been stored.

Download the project from above link and play around with it to learn more.

source code link :https://github.com/SpringMVCOrganization/springmvc-upload-file 

ref link : http://www.journaldev.com/2573/spring-mvc-file-upload-example-single-multiple-files

0 0
原创粉丝点击