Spring MVC 如何上传多个文件到指定位置

Spring MVC 如何上传多个文件到指定位置

太阳火神的美丽人生 (http://blog.csdn.net/opengl_es)

本文遵循“署名-非商业用途-保持一致”创作公用协议

转载请保留此句:太阳火神的美丽人生 -  本博客专注于 敏捷开发及移动和物联设备研究:iOS、Android、Html5、Arduino、pcDuino,否则,出自本博客的文章拒绝转载或再转载,谢谢合作。

Spring MVC Tutorial: How to Upload Multiple Files to Specific Location

SHORT LINK: 

Last Updated on February 10th, 2015 by Crunchify 22 Comments

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 and commons-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.

Add belwo to 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:

  1. crunchifyDisplayForm – It simply forwards request to the pageuploadfile.jsp
  2. 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.

CrunchifyFileUploadController.java
Java

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.

CrunchifyFileUpload.java
Java

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.

uploadfile.jsp

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>

uploadfilesuccess.jsp

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 ExamplesJava Examples.

Have anything to add to this article? Please chime in and join the conversion.

SHARE ON

TwitterFacebookGoogle+BufferPin ItFollow @Crunchify

Some more articles you might also be interested in …

  1. Spring MVC: How to Declare a Bean in Spring Application?
  2. Simplest Spring MVC Hello World Example / Tutorial – Spring Model – View – Controller Tips
  3. How to use AJAX, jQuery in Spring Web MVC (.jsp) – Example
  4. Working on Spring MVC Project? How to Report List of All Loaded Spring Beans during Startup?
  5. How to Update Sparkline Graph Every 3 Seconds in Spring MVC (Realtime Update)
  6. WordPress: How to Save Time on Files Upload
  7. Spring MVC: Introduction to Spring 3 MVC Framework – Spring 4
  8. Spring MVC: How to Access ModelMap Values in a JSP?
  9. Read config.properties value using Spring ‘singleton’ Scope in your Java Enterprise Application
  10. How to Sort List of Files based on Last Modified Time in Ascending and Descending?

Filed Under: EclipseJava CollectionSpring MVC TutorialsTagged: Controllerjavajava spring mvcjava upload filesspringSpring Architecturespring frameworkSpring MVCSpring MVC JQuery ExampleUpload Photos

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!

Enter your emailaddress... 


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.

时间: 2025-01-01 13:16:03

Spring MVC 如何上传多个文件到指定位置的相关文章

求助:summernote+spring mvc图片上传报错

问题描述 求助:summernote+spring mvc图片上传报错 先是controller代码: @ResponseBody @RequestMapping("/sumimg.do") public Result upload(HttpServletRequest request) { Result result = new Result(); // 转换为文件类型的request MultipartHttpServletRequest multipartRequest = (M

Spring MVC实现上传文件报错解决方案

报错代码: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.web.multipart.MultipartFile]: Specified class is an interface org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:101) o

spring mvc-Spring mvc 图片上传,求代码

问题描述 Spring mvc 图片上传,求代码 Spring mvc 图片上传,public void savePhoto(InputStream inputStream) throws Exception 里面怎么写 解决方案 Spring Mvc 上传图片代码spring MVC 上传图片 DEMOspring mvc 上传图片---------------------- 解决方案二: @RequestMapping("saveAdvertFile.action") public

mybatis-spring mvc批量上传功能

问题描述 spring mvc批量上传功能 springMVc+Spring+mybatis+mysql实现用户图片批量上传,为每一个用户创建一个名为id的文件夹用来存储图片.图片有大小限制.最多只能上传五张图片.最好有上传图片预览.前端主要使用jsp实现 谢谢 解决方案 你的具体问题是什么呢?你罗列的只是一些需求,这是不能得到有效回答的.

spring如何得到上传mongodb文件后的ID值??

问题描述 spring如何得到上传mongodb文件后的ID值?? 如何得到上传mongodb文件后的ID值??如何得到上传mongodb文件后的ID值?? 解决方案 http://blog.csdn.net/cuiran/article/details/8 希望这里有你想要的答案!

SpringMVC单文件上传、多文件上传、文件列表显示、文件下载(转)

  林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 本文详细讲解了SpringMVC实例单文件上传.多文件上传.文件列表显示.文件下载. 本文工程免费下载 一.新建一个Web工程,导入相关的包 springmvc的包+commons-fileupload.jar+connom-io.jar+commons-logging,jar+jstl.jar+standard.jar 整个相关的包如下: 整个工程目录如下: 二.配置web.xml和S

Struts+Spring+Hibernate实现上传下载

上传|下载 引言 文件的上传和下载在J2EE编程已经是一个非常古老的话题了,也许您马上就能掰着指头数出好几个著名的大件:如SmartUpload.Apache的FileUpload.但如果您的项目是构建在Struts+Spring+Hibernate(以下称SSH)框架上的,这些大件就显得笨重而沧桑了,SSH提供了一个简捷方便的文件上传下载的方案,我们只需要通过一些配置并辅以少量的代码就可以完好解决这个问题了. 本文将围绕SSH文件上传下载的主题,向您详细讲述如何开发基于SSH的Web程序.SS

上传多个文件的PHP脚本

脚本|上传 译者注:本文的原名是<Creating a Multi-File Upload Script in PHP>.我个个觉得这文章写得一般,代码也不是非常专业,但是它比较短,而且一时间也找不到好一点的文章,就把这个译过来了.其实PHP手册里也有一节是说多文件上传的,大家可以对比对比.文章内有的字句译出来不太顺眼,所以按照原意作了一定量的修改.本人水平有限,还望各位高手多指点. 导言     作为一个PHP的程序员,我曾遇到过这么一个客户,他需要一个可以同时上传多个文件的表单.因此,一天

用Struts上传多个文件的方法

上传     最近在做Struts项目时遇到了上传多个文件的问题.在网上查了不少资料,也没有找到用Struts上传多个文件的例子.我经过几天的研究,实现了用Struts上传多个文件的功能.现在贴出来让大家共享!     一.建立ActionForm package com.cnehu.struts.form;import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionError;impor