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 uploadMultipleFileHandler
method 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
- Spring MVC File Upload Example Tutorial – Single and Multiple Files
- Spring MVC Multiple File Upload example
- Spring MVC file upload example
- Spring MVC File Upload Example
- Spring MVC + Mybatis+MySQL File Upload and Download Example
- Struts 2 File Upload and Save Tutorial with Example
- input file upload multiple files
- Spring MVC with ParameterizableViewController Tutorial and Example
- ADF Single/Multiple files uploading and downloading
- spring mvc multipart file upload
- AjaxControlToolkit Multiple Files Upload
- Spring MVC 上传文件(upload files)
- Spring 4 MVC HelloWorld Tutorial – Full XML Example
- Spring MVC File Download Example
- Struts – Multiple configuration files example
- ADF Single/Multiple files uploading and downloading 在
- Upload multiple files Hotmail style
- Spring MVC 文件上传 file upload
- 今天做了一个获取获取wifi的mac的小demo
- 【腾讯bugly干货分享】Android自绘动画实现与优化实战——以Tencent OS录音机波形动
- 命令大全
- 异步I/O原理
- 搭建git服务器进行管理项目
- Spring MVC File Upload Example Tutorial – Single and Multiple Files
- OpenMP对临界区/变量的保护方法
- 在第一个字符串中删除在第二个字符串中出现的所有字符
- 初识JMS
- android:贝塞尔曲线简单实现
- 字符串1—字符串的旋转
- 华为机试---火眼金睛
- ElasticSearch Java Api(三) -更新索引库
- swust oj 1188 计算系数