关闭

利用 Spring MVC 上传多文件到指定目录 spring upload files

标签: springspring mvcjava webupload file
1687人阅读 评论(0) 收藏 举报
分类:
本篇文章,我们会教你通过eclipse构建一个创建一个Java web项目并转为maven工程,实现用spring mvc将所选文件上传到指定目录
开发环境:
1.JDK 1.7
2.Maven 3.3.9
3.Eclipse Mars.1
4.Spring 4.2.1.RELEASE
5.Spring MVC 4.2.1.RELEASE
6.Tomcat7

1.目录结构

2. 创建项目
Eclipse - File - New - Dynamic Web Project 输入项目名称,然后右击该项目Configure-Convert to Maven project
在WebContent/WEB-INF下新建一个web.xml文件
3.pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.thinkingingis</groupId>
  <artifactId>SpringUploadFiles</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
   <dependencies>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-context</artifactId>
  		<version>4.2.1.RELEASE</version>
  	</dependency>
  	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-aop</artifactId>
		<version>4.2.1.RELEASE</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-webmvc</artifactId>
		<version>4.2.1.RELEASE</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-web</artifactId>
		<version>4.2.1.RELEASE</version>
	</dependency>
	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>jstl</artifactId>
		<version>1.2</version>
	</dependency>
	<!-- fileupload -->
	<dependency>
		<groupId>commons-fileupload</groupId>
		<artifactId>commons-fileupload</artifactId>
		<version>1.2</version>
	</dependency>
	<!-- io -->
	<dependency>
		<groupId>commons-io</groupId>
		<artifactId>commons-io</artifactId>
		<version>1.4</version>
	</dependency>
  </dependencies>
</project>
4.ThinkFileUpload.java
这个类用来存放MultipartFile类型的对象,这是spring framework提供的一个用于接收所上传文件内容的类。
package org.thinkingingis.form;

import java.util.List;

import org.springframework.web.multipart.MultipartFile;

public class ThinkFileUpload {
	private List<MultipartFile> thinkFiles;
	 
    public List<MultipartFile> getFiles() {
        return thinkFiles;
    }
 
    public void setFiles(List<MultipartFile> files) {
        this.thinkFiles = files;
    }
}
5.FileUploadController.java 拥有两个方法

thinkDisplayForm -- 返回上传文件的页面

crunchifySave -- 用于接收文件并保存文件到指定目录,这里保存在/Users/gisboy/node/ 目录下

package org.thinkingingis.controller;

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;
import org.thinkingingis.form.ThinkFileUpload;

@Controller
public class FileUploadController {
	
	@RequestMapping(value = "/upload", method = RequestMethod.GET)
	public String thinkDisplayForm(){
		//从 index.jsp 拦截请求,请求名称为  : /upload
		return "uploadfile";
	}
	
    @RequestMapping(value = "/savefiles", method = RequestMethod.POST)
    public String crunchifySave(
            @ModelAttribute("uploadForm") ThinkFileUpload uploadForm,
            Model map) throws IllegalStateException, IOException {
       
    	//文件的存放路径
    	String saveDirectory = "/Users/gisboy/node/";
 
        List<MultipartFile> thinkFiles = uploadForm.getFiles();
 
        List<String> fileNames = new ArrayList<String>();
 
        if (null != thinkFiles && thinkFiles.size() > 0) {
            for (MultipartFile multipartFile : thinkFiles) {
 
                String fileName = multipartFile.getOriginalFilename();
                if (!"".equalsIgnoreCase(fileName)) {
                
                    multipartFile.transferTo(new File(saveDirectory + fileName));
                    fileNames.add(fileName);
                }
            }
        }
        map.addAttribute("files", fileNames);
        return "uploadfilesuccess";
    }
}
6.jsp文件

index.jsp

<html>
<head>
<title>Spring Upload Files by ThinkingInGIS</title>
<style type="text/css">
body {
	background-image: url(./resources/bg.png);
}
</style>
</head>
<body>
	<br>
	<div style="text-align:center">
		<h2>
			Hey Buddy..!! This is a Spring MVC Demo<br> <br>
		</h2>
		<h3>
			<a href="upload.html">Click here to Jump to file upload page... </a>
		</h3>
	</div>
</body>
</html>

uploadfile.jsp

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>上传文件</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;
            	console.log(fileIndex);
                $('#fileTable').append('<tr><td>' + '<input type="file" name="files[' + fileIndex + ']" />' + '</td></tr>');
            });

     });
</script>
<style type="text/css">
	body {
	    background-image:
	        url(bg.png);
	}
</style>
</head>
<body>
<br>
    <br>
    <div align="center">
        <h1>ThinkingInGIS - 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

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>ThinkingInGIS - Upload Multiple Files Example</title>
<style type="text/css">
body {
    background-image:
        url(bg.png);
}
</style>
</head>
<body>
    <br>
    <br>
    <div align="center">
 
        <h1>ThinkingInGIS - Spring MVC Upload Multiple Files Example</h1>
        <p>Following files are uploaded successfully.</p>
        <ol>
            <c:forEach items="${files}" var="file">
           - ${file} <br>
            </c:forEach>
        </ol>
        <a href="http://localhost:8080/SpringUploadFiles/index.jsp"><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='https://github.com/ThinkingInGIS/'>ThinkingInGIS</a>. Click <a
                href='https://github.com/ThinkingInGIS/SpringUploadFiles'>here</a>
           to get source code.<br>
        </div>
    </div>
</body>
</html>

7.web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>SpringUploadFiles</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
    <servlet>
        <servlet-name>springuploadfiles</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springuploadfiles</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
  
</web-app>

8.springuploadfiles-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
	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.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd">
 
	<context:component-scan base-package="org.thinkingingis.controller" />
 	
 	
 	<bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
        
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.UrlBasedViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>
	
	
 
</beans>

9.完成之后启动项目

在浏览器中输入 http://localhost:8080/SpringUploadFiles/

运行截图如下:


点击链接 跳转到upload页面,选择待上传的文件


文件上传成功页面:

指定路径下的文件:


至此,一个通过简单的利用spring mvc 上传多文件的小程序就完成啦。

(如遇到问题,请留言给作者,以便共同探讨gis知识。thinkingingis@qq.com
微信公众号:ThinkingInGIS

欢迎大家关注:)
1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:50879次
    • 积分:881
    • 等级:
    • 排名:千里之外
    • 原创:36篇
    • 转载:0篇
    • 译文:0篇
    • 评论:23条
    微信公众号
    ThinkingInGIS
    文章分类