Spring MVC 怎么上传多个文件到指定位置
Spring MVC 如何上传多个文件到指定位置
太阳火神的美丽人生 (http://blog.****.net/opengl_es)
本文遵循“署名-非商业用途-保持一致”创作公用协议
转载请保留此句:太阳火神的美丽人生 - 本博客专注于 敏捷开发及移动和物联设备研究:iOS、Android、Html5、Arduino、pcDuino,否则,出自本博客的文章拒绝转载或再转载,谢谢合作。
SHORT LINK: Last Updated on February 10th, 2015 by Crunchify 22 CommentsSpring MVC Tutorial: How to Upload Multiple Files to Specific Location
This is another complete Spring MVC tutorial which accepts file on Upload form and copy it to specificfolder on “Submit” event. As usual we have a dependency
on Hello World Spring MVC Example.
So, these are the additions / changes we need to perform in this example:
- New file: CrunchifyFileUploadController.java
- New file: CrunchifyFileUpload.java
- New file: uploadfile.jsp
- New file: uploadfilesuccess.jsp
- Modified file: crunchify-servlet.xml
- 2 new jar files:
commons-io-2.4.jar
andcommons-fileupload-1.3.jar
Here is a final project structure so you will get some idea on where to add files.
Now let’s get started:
Step1: Pre-Requisite:
http://crunchify.com/hello-world-example-spring-mvc-3-2-1/ (Deploy this project successfully onTomcat)
Maven Dependencies:
Add below new dependencies to your project’s pom.xml
file.
1
2
3
4
5
6
7
8
9
10
|
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.4</version>
</dependency>
|
Step2: SpringController
Create a Spring 3 MVC based controller which handles file upload. There are two methods in thiscontroller:
-
crunchifyDisplayForm
– It simply forwards request to the pageuploadfile.jsp -
crunchifySave
– Fetches the form using@ModelAttribute
annotation and get the File content from it. It creates a list of filenames of files being uploaded and pass this list to success page.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
package com.crunchify.controller;
import com.crunchify.form.CrunchifyFileUpload;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class CrunchifyFileUploadController {
@RequestMapping(value = "/upload", method = RequestMethod.GET)
public String crunchifyDisplayForm() {
return "uploadfile";
}
@RequestMapping(value = "/savefiles", method = RequestMethod.POST)
public String crunchifySave(
@ModelAttribute("uploadForm") CrunchifyFileUpload uploadForm,
Model map) throws IllegalStateException, IOException {
String saveDirectory = "c:/crunchify/";
List<MultipartFile> crunchifyFiles = uploadForm.getFiles();
List<String> fileNames = new ArrayList<String>();
if (null != crunchifyFiles && crunchifyFiles.size() > 0) {
for (MultipartFile multipartFile : crunchifyFiles) {
String fileName = multipartFile.getOriginalFilename();
if (!"".equalsIgnoreCase(fileName)) {
// Handle file content - multipartFile.getInputStream()
multipartFile
.transferTo(new File(saveDirectory + fileName));
fileNames.add(fileName);
}
}
}
map.addAttribute("files", fileNames);
return "uploadfilesuccess";
}
}
|
Step3: Model – Form Object
Create a Java bean which acts as Model/Form object for our Spring application. This bean contains a List
of org.springframework.web.multipart.MultipartFile
objects. Spring framework provides a useful class MultipartFile which can be used to fetch the file content of uploaded file. Apart from its content, the MultipartFile object also gives you other useful information such as filename, file size etc.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
package com.crunchify.form;
import java.util.List;
import org.springframework.web.multipart.MultipartFile;
public class CrunchifyFileUpload {
private List<MultipartFile> crunchifyFiles;
public List<MultipartFile> getFiles() {
return crunchifyFiles;
}
public void setFiles(List<MultipartFile> files) {
this.crunchifyFiles = files;
}
}
|
Step4: JSP Views
Now create the view pages for this application. We will need two JSPs, one to display file upload form and another to show result on successful upload.
The uploadfile.jsp
displays a form with file input. Apart from this we have added small jquery snippetonclick of Add button. This will add a new file input component at the end of form. This allows user toupload as many files as they want.
Note that we have set enctype=”multipart/form-data”
attribute of our <form>
tag.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Crunchify - Spring MVC Upload Multiple Files Example</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(document)
.ready(
function() {
//add more file components if Add is clicked
$('#addFile')
.click(
function() {
var fileIndex = $('#fileTable tr')
.children().length - 1;
$('#fileTable')
.append(
'<tr><td>'
+ ' <input type="file" name="files['+ fileIndex +']" />'
+ '</td></tr>');
});
});
</script>
<style type="text/css">
body {
background-image:
url('http://cdn3.crunchify.com/wp-content/uploads/2013/03/Crunchify.bg_.300.png');
}
</style>
</head>
<body>
<br>
<br>
<div align="center">
<h1>Crunchify - Spring MVC Upload Multiple Files Example</h1>
<form:form method="post" action="savefiles.html"
modelAttribute="uploadForm" enctype="multipart/form-data">
<p>Select files to upload. Press Add button to add more file
inputs.</p>
<table id="fileTable">
<tr>
<td><input name="files[0]" type="file" /></td>
</tr>
<tr>
<td><input name="files[1]" type="file" /></td>
</tr>
</table>
<br />
<input type="submit" value="Upload" />
<input id="addFile" type="button" value="Add File" />
</form:form>
<br />
</div>
</body>
</html>
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>Crunchify - Upload Multiple Files Example</title>
<style type="text/css">
body {
background-image:
url('http://cdn3.crunchify.com/wp-content/uploads/2013/03/Crunchify.bg_.300.png');
}
</style>
</head>
<body>
<br>
<br>
<div align="center">
<h1>Crunchify - Spring MVC Upload Multiple Files Example</h1>
<p>Awesome.. Following files are uploaded successfully.</p>
<ol>
<c:forEach items="${files}" var="file">
- ${file} <br>
</c:forEach>
</ol>
<a href="http://localhost:8080/CrunchifySpringMVC3.2.1/upload.html"><input
type="button" value="Go Back" /></a> <br />
<br />
<br />
<div
style="font-family: verdana; line-height: 25px; padding: 5px 10px; border-radius: 10px; border: 1px dotted #A4A4A4; width: 50%; font-size: 12px;">
Spring MVC Upload Multiple Files Example by <a
href='http://crunchify.com'>Crunchify</a>. Click <a
href='http://crunchify.com/category/java-web-development-tutorial/'>here</a>
for all Java, Spring MVC, Web Development examples.<br>
</div>
</div>
</body>
</html>
|
Step5: Update Spring Configuration
Add below bean to crunchify-servlet.xml
file, just above <beanid="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
line.
1
2
|
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
|
Step6: Checkout Result
Start tomcat and point your browser to this URL: http://localhost:8080/CrunchifySpringMVC3.2.1/upload.html and you should see screen similar tothis.
After file upload you will see success message like this. You can always beautify your .jsp file the wayyou want.
List of all Spring MVC Examples, Java Examples.
SHARE ON
TwitterFacebookGoogle+BufferPin ItFollow @CrunchifySome more articles you might also be interested in …
- Spring MVC: How to Declare a Bean in Spring Application?
- Simplest Spring MVC Hello World Example / Tutorial – Spring Model – View – Controller Tips
- How to use AJAX, jQuery in Spring Web MVC (.jsp) – Example
- Working on Spring MVC Project? How to Report List of All Loaded Spring Beans during Startup?
- How to Update Sparkline Graph Every 3 Seconds in Spring MVC (Realtime Update)
- WordPress: How to Save Time on Files Upload
- Spring MVC: Introduction to Spring 3 MVC Framework – Spring 4
- Spring MVC: How to Access ModelMap Values in a JSP?
- Read config.properties value using Spring ‘singleton’ Scope in your Java Enterprise Application
- How to Sort List of Files based on Last Modified Time in Ascending and Descending?
Enjoyed this post?
Be sure to subscribe to the Crunchify newsletter and get regular updates about awesomeposts just like this one and more! Join more than 13000 subscribers!
About Crunchify
Hello & Good Day from greater New York. Crunchify is founded by App Shah. He is a professional blogger & loves Web development hence Crunchify.com is his publication with more than 10 millions pageviews per month, that covers all aspects and tactics on Java, WordPress, J2EE (Enterprise Java), Spring MVC, Github, etc Technologies.
相关推荐
- Spring MVC 怎么上传多个文件到指定位置
- Angular 四 上传多个文件到Spring boot
- 怎么用java程序实现上传文件到指定的URL地址
- Django基础 3.1 注册应用 3.2 后端跨域 3.2.1 安装corsheaders 3.2.2 注册 3.2.3 增加中间件 corsheaders.middleware.CorsMiddleware需要在CommonMiddleware在他上面 3.2.4 允许所有的源跨域 配置数据库 项目本地化 静态文件位置 指定文件上传的位置 一级路由/系统路由 二级路由/应用路由 ModelSerializer 继承 Serializer 一对多 正向读值(站在外键的这个类中) 对象.外键.关联类的字段 反向读值(站在类的角度上来获取这个类下有什么商品) 对象.类名的小写_set.all() 多对多 一个商品属于多个类 一个类下有多个商品 正向取值(商品属于哪个类?) 反向取值(这个类下有多少商品) 0 获取当前页 1 导包 2 获取需要分页的数据 3 实例化分页 2 自定义中间件 2 3 注册到settings.py
- 客户端上传记事本到服务器端的指定的文件夹怎么实现
- winform 怎么上传文件到指定url,或者iis里面
- spring mvc 后台数据存储到session 避免多个人同时操作出现信息不可用 怎么做
- 请问一些关于文件对象的有关问题,怎么复制某文件夹下的特定文件到指定位置
- 怎么根据文件地址批量复制文件到指定位置
- 安装IIS和.net framework3.5一个或多个安装选项在目标服务器上缺少源文件的解决方法 windows2012服务器在安装IIS8.5时,系统报错,提示:安装一个或多个角色、角色服务或功能失败或者一个或多个安装选项在目标服务器上缺少源文件,或者找不到源文件。请在尝试在新的“添加角色和功能”向导会话中安装角色、角色服务或功能,然后在向导的“确认”页中单击“指定备用源路径”以指定安装所需的源文件的有效位置。目标服务器的计算机账户必须能够访问该位置。怎么解决呢?
- springMVC controller层注解开发之常见引文
-
关于Assertion