天天看點

Spring MVC 如何上傳多個檔案到指定位置Spring MVC Tutorial: How to Upload Multiple Files to Specific Location

Spring MVC 如何上傳多個檔案到指定位置

<a target="_blank" href="http://blog.csdn.net/opengl_es">轉載請保留此句:太陽火神的美麗人生 -  本部落格專注于 靈活開發及移動和物聯裝置研究:iOS、Android、Html5、Arduino、pcDuino,否則,出自本部落格的文章拒絕轉載或再轉載,謝謝合作。</a>

SHORT LINK: 

Spring MVC 如何上傳多個檔案到指定位置Spring MVC Tutorial: How to Upload Multiple Files to Specific Location

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: <code>commons-io-2.4.jar</code> and <code>commons-fileupload-1.3.jar</code>

Here is a final project structure so you will get some idea on where to add files.

Spring MVC 如何上傳多個檔案到指定位置Spring MVC Tutorial: How to Upload Multiple Files to Specific Location

Add below new dependencies to your project’s <code>pom.xml</code> file.

Add belwo to pom.xml file

1

2

3

4

5

6

7

8

9

10

&lt;dependency&gt;

&lt;groupId&gt;commons-fileupload&lt;/groupId&gt;

&lt;artifactId&gt;commons-fileupload&lt;/artifactId&gt;

&lt;version&gt;1.2&lt;/version&gt;

&lt;/dependency&gt;

&lt;groupId&gt;commons-io&lt;/groupId&gt;

&lt;artifactId&gt;commons-io&lt;/artifactId&gt;

&lt;version&gt;1.4&lt;/version&gt;

Create a Spring 3 MVC based controller which handles file upload. There are two methods in thiscontroller:

<code>crunchifyDisplayForm</code> – It simply forwards request to the pageuploadfile.jsp

<code>crunchifySave</code> – Fetches the form using <code>@ModelAttribute</code> 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.javaJava

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&lt;MultipartFile&gt; crunchifyFiles = uploadForm.getFiles();

        List&lt;String&gt; fileNames = new ArrayList&lt;String&gt;();

        if (null != crunchifyFiles &amp;&amp; crunchifyFiles.size() &gt; 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";

}

Create a Java bean which acts as Model/Form object for our Spring application. This bean contains a <code>List</code> of <code>org.springframework.web.multipart.MultipartFile</code> 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.javaJava

package com.crunchify.form;

public class CrunchifyFileUpload {

    private List&lt;MultipartFile&gt; crunchifyFiles;

    public List&lt;MultipartFile&gt; getFiles() {

        return crunchifyFiles;

    public void setFiles(List&lt;MultipartFile&gt; files) {

        this.crunchifyFiles = files;

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 <code>uploadfile.jsp</code> 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 <code>enctype=”multipart/form-data”</code> attribute of our <code>&lt;form&gt;</code> tag.

uploadfile.jsp

52

53

54

55

56

57

58

59

60

61

&lt;%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%&gt;

&lt;html&gt;

&lt;head&gt;

&lt;title&gt;Crunchify - Spring MVC Upload Multiple Files Example&lt;/title&gt;

&lt;script

    src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"&gt;&lt;/script&gt;

&lt;script&gt;

    $(document)

            .ready(

                    function() {

                        //add more file components if Add is clicked

                        $('#addFile')

                                .click(

                                        function() {

                                            var fileIndex = $('#fileTable tr')

                                                    .children().length - 1;

                                            $('#fileTable')

                                                    .append(

                                                            '&lt;tr&gt;&lt;td&gt;'

                                                                    + '   &lt;input type="file" name="files['+ fileIndex +']" /&gt;'

                                                                    + '&lt;/td&gt;&lt;/tr&gt;');

                                        });

                    });

&lt;/script&gt;

&lt;style type="text/css"&gt;

body {

    background-image:

        url('http://cdn3.crunchify.com/wp-content/uploads/2013/03/Crunchify.bg_.300.png');

&lt;/style&gt;

&lt;/head&gt;

&lt;body&gt;

    &lt;br&gt;

    &lt;div align="center"&gt;

        &lt;h1&gt;Crunchify - Spring MVC Upload Multiple Files Example&lt;/h1&gt;

        &lt;form:form method="post" action="savefiles.html"

            modelAttribute="uploadForm" enctype="multipart/form-data"&gt;

            &lt;p&gt;Select files to upload. Press Add button to add more file

                inputs.&lt;/p&gt;

            &lt;table id="fileTable"&gt;

                &lt;tr&gt;

                    &lt;td&gt;&lt;input name="files[0]" type="file" /&gt;&lt;/td&gt;

                &lt;/tr&gt;

                    &lt;td&gt;&lt;input name="files[1]" type="file" /&gt;&lt;/td&gt;

            &lt;/table&gt;

            &lt;br /&gt;

            &lt;input type="submit" value="Upload" /&gt;

            &lt;input id="addFile" type="button" value="Add File" /&gt;

        &lt;/form:form&gt;

        &lt;br /&gt;

    &lt;/div&gt;

&lt;/body&gt;

&lt;/html&gt;

uploadfilesuccess.jsp

&lt;%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%&gt;

&lt;title&gt;Crunchify - Upload Multiple Files Example&lt;/title&gt;

        &lt;p&gt;Awesome.. Following files are uploaded successfully.&lt;/p&gt;

        &lt;ol&gt;

            &lt;c:forEach items="${files}" var="file"&gt;

           - ${file} &lt;br&gt;

            &lt;/c:forEach&gt;

        &lt;/ol&gt;

        &lt;a href="http://localhost:8080/CrunchifySpringMVC3.2.1/upload.html"&gt;&lt;input

            type="button" value="Go Back" /&gt;&lt;/a&gt; &lt;br /&gt;

        &lt;div

            style="font-family: verdana; line-height: 25px; padding: 5px 10px; border-radius: 10px; border: 1px dotted #A4A4A4; width: 50%; font-size: 12px;"&gt;

            Spring MVC Upload Multiple Files Example by &lt;a

                href='http://crunchify.com'&gt;Crunchify&lt;/a&gt;. Click &lt;a

                href='http://crunchify.com/category/java-web-development-tutorial/'&gt;here&lt;/a&gt;

            for all Java, Spring MVC, Web Development examples.&lt;br&gt;

        &lt;/div&gt;

Add below bean to <code>crunchify-servlet.xml</code>  file, just above  <code>&lt;beanid="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"&gt;</code>  line.

&lt;bean id="multipartResolver"

        class="org.springframework.web.multipart.commons.CommonsMultipartResolver" /&gt;

Spring MVC 如何上傳多個檔案到指定位置Spring MVC Tutorial: How to Upload Multiple Files to Specific Location

After file upload you will see success message like this. You can always beautify your .jsp file the wayyou want.

Spring MVC 如何上傳多個檔案到指定位置Spring MVC Tutorial: How to Upload Multiple Files to Specific Location

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

<a target="_blank" href="http://crunchify.com/spring-mvc-how-to-declare-a-bean-in-spring-application/">Spring MVC: How to Declare a Bean in Spring Application?</a>

<a target="_blank" href="http://crunchify.com/simplest-spring-mvc-hello-world-example-tutorial-spring-model-view-controller-tips/">Simplest Spring MVC Hello World Example / Tutorial – Spring Model – View – Controller Tips</a>

<a target="_blank" href="http://crunchify.com/how-to-use-ajax-jquery-in-spring-web-mvc-jsp-example/">How to use AJAX, jQuery in Spring Web MVC (.jsp) – Example</a>

<a target="_blank" href="http://crunchify.com/working-on-spring-mvc-project-how-to-report-list-of-all-loaded-spring-beans-during-startup/">Working on Spring MVC Project? How to Report List of All Loaded Spring Beans during Startup?</a>

<a target="_blank" href="http://crunchify.com/how-to-update-sparkline-graph-every-3-seconds-in-spring-mvc-realtime-update/">How to Update Sparkline Graph Every 3 Seconds in Spring MVC (Realtime Update)</a>

<a target="_blank" href="http://crunchify.com/wordpress-how-to-save-time-on-files-upload/">WordPress: How to Save Time on Files Upload</a>

<a target="_blank" href="http://crunchify.com/spring-mvc-introduction-to-spring-3-mvc-framework/">Spring MVC: Introduction to Spring 3 MVC Framework – Spring 4</a>

<a target="_blank" href="http://crunchify.com/spring-mvc-how-to-access-modelmap-values-in-a-jsp/">Spring MVC: How to Access ModelMap Values in a JSP?</a>

<a target="_blank" href="http://crunchify.com/read-config-properties-value-using-spring-singleton-scope-in-your-java-enterprise-application/">Read config.properties value using Spring ‘singleton’ Scope in your Java Enterprise Application</a>

<a target="_blank" href="http://crunchify.com/how-to-sort-list-of-files-based-on-last-modified-time-in-ascending-and-descending/">How to Sort List of Files based on Last Modified Time in Ascending and Descending?</a>

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

Spring MVC 如何上傳多個檔案到指定位置Spring MVC Tutorial: How to Upload Multiple Files to Specific Location