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 Examples, Java Examples.

Have anythingtoaddtothis 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: Eclipse, Java Collection, Spring MVC TutorialsTagged: Controller, java, java spring mvc, java upload files, spring, Spring Architecture, spring framework, Spring MVC, Spring MVC JQuery Example, Upload 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...


http://www.taodudu.cc/news/show-2936553.html

相关文章:

  • openstack项目中遇到的各种问题总结 其一(问题多多)
  • 使用setViewControllers实现一些不同寻常的跳转
  • TP5.1自定义创建命令(php think make:controller app\index\User)
  • java几个注解的作用及比较(@RestController、@Controller、@ResponseBody、@RequestBody等)
  • restcontrol 注解
  • java controller注解原理_SpringMVC运行流程与原理【Controller接口实现注解实现】
  • SpringMVC基础学习之Controller的两种实现方式和RequstMapping注解的使用
  • Controller层各注解总结
  • Autonomous automobile trajectory tracking for off-road driving翻译学习
  • UIScrollview UIPageViewCon troller
  • Review Troller
  • 一款App的开发成本是多少?
  • 机器人开始“杀人”了
  • 美通企业日报 | 无锡国际生命科学创新园开园;本特勒与恒大汽车博世实现合作...
  • 声网 Agora 的 2019
  • 软件开发的那些坑,你跳了没?这篇文章价值千万(一)
  • open_source_team
  • 互联网早报:滴滴正式启动造车,滴滴副总裁、小桔车服总经理杨峻负责
  • 两轮换电领域的“苹果”,“换换”能成吗?
  • 数据仓库面试总结大全,深度解析底层逻辑
  • 2022年全新数据仓库面试总结大全
  • 科技爱好者周刊(第 212 期):人生不短
  • 共享单车上的智能锁,做出来有多难?
  • 物联网企业争抢「两轮车换电」赛道
  • TiDB 在特来电的实践
  • 美团技术分享:大众点评App的短视频耗电量优化实战
  • 四大思维工具,SWOT、PDCA、DISC、时间管理
  • PCB简单板框绘制
  • cmmi实践访谈测试ppt_CMMI模型基础知识考试试题-(标准答案).xls
  • 【干货收藏】数据分析师必备的20种分析思维

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

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

    Spring MVC实现上传文件报错解决方案 参考文章: (1)Spring MVC实现上传文件报错解决方案 (2)https://www.cnblogs.com/liuling/p/2014-3-5 ...

  2. spring mvc(注解)上传文件的简单例子

    spring mvc(注解)上传文件的简单例子,这有几个需要注意的地方 1.form的enctype="multipart/form-data" 这个是上传文件必须的 2.appl ...

  3. 怎么用git将本地代码上传到远程服务器_git之如何把本地文件上传到远程仓库的指定位置...

    2018.11.26添加内容: 对于自己的仓库,我们建议将远程仓库通过clone命令把整个仓库克隆到本地的某一路径下.这样的话我们从本地向远程仓库提交代码时,就可以直接把需要提交的文件拖到我们之前克隆 ...

  4. spring mvc + ajax上传文件,页面局部刷新

    1.点击上传按钮进行如下操作,通过表单名称以及input名称获取相应的值,对于上传的文件,使用.files来获取, 因为包含文件的上传,所以采用FormData的形式来进行数据交互,通过append将 ...

  5. spring mvc 附件上传至腾讯云qcloud

    简单记录主要是便于自己用,有需要的参考一下... 上传至腾讯云,相关文档参阅官方文档 附件为比较早的版本,自己修改过 1.实体bean --用multipartFile接收 public class ...

  6. Spring MVC 3:上传多个文件

    只是在办公室又漫长的一天,数据库不可用,一个团队成员现在滞后一周. 因此,我们必须作为一个团队来交付它. 在Spring3,它看起来很直接上传文件. 但是,从jsp文件上载多个文件几乎没有帮助. 上载 ...

  7. SSM框架之Spring MVC(三)http响应、文件上传

    一.响应数据和结果视图 1.1 返回值分类 1.1.1 字符串 创建实体类和controller类 实体类User package cn.xiaomifeng1010.domain;import ja ...

  8. C# ASP.NET MVC 图片上传的多种方式(存储至服务器文件夹,阿里云oss)

    图片上传时我们进场用到的一个功能今天将他整理了一下写了个demo希望对大家有用 该demo分为如下 1.上传至至服务器文件夹 2.上传至阿里云oss 3.百度webupload上传图片 效果图如下: ...

  9. Spring Boot (30) 上传文件

    文件上传 上传文件和下载文件是Java Web中常见的一种操作,文件上传主要是将文件通过IO流传输到服务器的某一个文件夹下. 导入依赖 在pom.xml中添加上spring-boot-starter- ...

最新文章

  1. 验证用户身份Filter过滤器
  2. Kinect开发资源汇总
  3. OJ 169 Majority Element
  4. 有的时候不评价别人其实挺难的
  5. 海思加鸿蒙的零距离思考,自主生态之路在何方
  6. Dtree 添加 checkbox 复选框 可以默认选中
  7. Java 将鼠标改为图片的两种方法
  8. 安装mysql8.0.11
  9. k3修改服务器,金蝶k3客户端修改服务器地址
  10. 阿里播放器的使用Aliplayer
  11. 微信卡券 java_微信卡券功能JAVA版(PS : 其實無關乎什么語言拉 :) )
  12. HM5469A单节锂电池保护IC过流9A电流可以做8W
  13. Spring注入Bean的几种方法
  14. oracle ebs fsg报表,Oracle EBS FSG报表迁移
  15. pat乙级1087C语言
  16. 飞机大战--java
  17. CGAL 凹包(alpha-Shape)
  18. 金仓数据库 时间没有 时分秒 的问题
  19. pfa100_PFA 的主要性能
  20. 把oracle11g数据导入19c,oracle11g2oracle11g oracle11g2oracle19c

热门文章

  1. UCOS-Ⅲ:软件定时器
  2. vue中实现动画效果--三种方式
  3. 汇编 浮点指令FLD,FSTP,FADD与FPU寄存器
  4. python题库刷题网站_python在线刷题网站
  5. kali搭建Linux版本的小皮面板
  6. 面试笔试题中的LRU算法及其缺页次数替换
  7. 宫崎骏魔幻动画电影《哈尔的移动城堡》高清720P,国粤日三语
  8. 微信小程序中的onLoad
  9. oracle无法打开12560
  10. 支持 C++11/14/17 功能(现代 C++