Springmvc文件上传(1)

Springmvc文件上传

依赖的jar包

commons-io
commons-upload

Spring 核心依赖包:bean context aop context core web webmvc expression

web.xml相关配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	id="WebApp_ID" version="3.1">
	<display-name>springmvc_upload</display-name>
	<filter>
		<filter-name>characterencoding</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>characterencoding</filter-name>
		<url-pattern>*.do</url-pattern>
	</filter-mapping>
	<servlet>
		<servlet-name>upload</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:mvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>upload</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
</web-app>

注意点:

  • springmvc的核心配置文件一定在DispatcherServlet处配置其具体位置,而不是
  • 映射的虚拟路径可以是"/"、"/"、".do"等,但是不要写成"/*.do"

springmvc核心配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
	<!-- 开启mvc的注解 -->
	<mvc:annotation-driven />
	<!-- 扫描包 -->
	<context:component-scan base-package="com.zrm.controller"></context:component-scan>
	<!-- 配置视图解析器 -->
	<bean id="InternalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
	<!-- 配置文件解析器 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="utf-8"></property>
		<property name="maxUploadSize" value="10240000"></property>
		<property name="maxInMemorySize" value="4096000"></property>
	</bean>
</beans>

注意点:

  • 上传的文件大小不得超过文件解析器中maxUploadSize设置的大小,否则会报错
  • 若是在web.xml的url-pattern中设置如/拦截了静态资源,可在此处添加类似<mvc:resources location="/" mapping="//.js"></mvc:resources>这样的设置来放行静态资源,最好把静态资源放置在wencontent下而非WEB-INF(访问权限受限)

单文件上传

controller层Java代码

@Controller
public class UploadCtrl {
	@RequestMapping("/toUpload.do")
	public String toUpload() {
		return "upload";
	}
	@RequestMapping("/upload.do")
	public ModelAndView upload(HttpServletRequest req,@RequestParam("file")CommonsMultipartFile file) {
		String path = req.getServletContext().getRealPath("/upload");
		String name = file.getOriginalFilename();
		System.out.println("文件名:"+name);
		InputStream is = null;
		OutputStream os = null;
		try {
			is = file.getInputStream();
			os = new FileOutputStream(new File(path,name));
			byte[] bytes = new byte[1024];
			int len =0;
			while((len=is.read(bytes))!=-1) {
				os.write(bytes,0,len);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				if(is!=null)
					is.close();
				if(os!=null)
					os.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		   return new ModelAndView("index");
	}

注意点:

  • CommonsMultipartFile file处必须使用注解@RequestParam(“file”)为其注入请求中的file属性值,否则CommonsMultipartFile会自己去尝试初始化file,从而报错(找不到CommonsMultipartFile的file值)
  • 通过 “String path = req.getServletContext().getRealPath(”/upload");" 将"/upload"这个虚拟路径映射为webcontent下的真实路径。

相关jsp代码:upload.jsp

<body>
    <form action="upload.do" method="post" enctype="multipart/form-data">
    	file:<input type="file" name="file"/><input type="submit" value="上传"/>
    </form>
 </body>

多文件批量上传

controller层Java代码

@RequestMapping("/toBatchUpload.do")
	public String toBatchUpload() {
		return "batchUpload";
	}
	@RequestMapping("/batchUpload.do")
	public ModelAndView batchUpload(HttpServletRequest req,@RequestParam("file")CommonsMultipartFile[] file) {
		String path = req.getServletContext().getRealPath("/upload");
		String name = null;
		InputStream is = null;
		OutputStream os = null;
			byte[] bytes = new byte[1024];
			int len =0;
			for (int i = 0; i < file.length; i++) {
				try {
					name = file[i].getOriginalFilename();
					is = file[i].getInputStream();
					System.out.println("文件名:"+name);
					os = new FileOutputStream(new File(path,name));
					while((len=is.read(bytes))!=-1) {
						os.write(bytes,0,len);
					}
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}finally {
					try {
						if(is!=null)
							is.close();
						if(os!=null)
							os.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			return new ModelAndView("index");
	}

通过for循环,重复执行单文件上传代码

相关jsp代码:batchUpload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Home Page</title>
    <script src="${pageContext.request.contextPath }/js/jquery-2.1.0.min.js" type="text/javascript"></script>
</head>
<body>
    <form action="batchUpload.do" method="post"  >
    	file:<input type="file" name="file"/>
    	<input id="add" type="button" value="添加">
    	<input type="submit" value="上传"/>
    	<div id="fileList"></div>
    </form>
 </body>
 <script type="text/javascript">
	 $("#add").click(function(){
	 		var field = "<p>选择文件:<input type='file' name='file'/><input type='button' value='删除 '  οnclick='del(this);' /></p>";
	 		$("#fileList").append(field);
	 	});
	 function del(obj){
		 $(obj).parent().remove();
	 };
 </script>
</html>

index.jsp

<body>
上传成功
</body>

注意点:

  • jquery的基本语法就是以function,所以del()函数需要单独定义,而不能将其嵌套在$().ready里面。总结起来就是,使用时可嵌套,但是定义时不可嵌套
  • enctype="multipart/form-data"上传的文件类型不能忘了

项目结构

springmvc_upload

body>
上传成功

``` **注意点:** - jquery的基本语法就是以function,所以del()函数需要单独定义,而不能将其嵌套在$().ready里面。总结起来就是,使用时可嵌套,但是定义时不可嵌套 - enctype="multipart/form-data"上传的文件类型不能忘了 ## 项目结构 [外链图片转存中...(img-VUKrDGZF-1567076823417)]

项目源码已上传至 github fileupload

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于计算机专业的学生而言,参加各类比赛能够带来多方面的益处,具体包括但不限于以下几点: 技能提升: 参与比赛促使学生深入学习和掌握计算机领域的专业知识与技能,如编程语言、算法设计、软件工程、网络安全等。 比赛通常涉及实际问题的解决,有助于将理论知识应用于实践中,增强问题解决能力。 实践经验: 大多数比赛都要求参赛者设计并实现解决方案,这提供了宝贵的动手操作机会,有助于积累项目经验。 实践经验对于计算机专业的学生尤为重要,因为雇主往往更青睐有实际项目背景的候选人。 团队合作: 许多比赛鼓励团队协作,这有助于培养学生的团队精神、沟通技巧和领导能力。 团队合作还能促进学生之间的知识共享和思维碰撞,有助于形成更全面的解决方案。 职业发展: 获奖经历可以显著增强简历的吸引力,为求职或继续深造提供有力支持。 某些比赛可能直接与企业合作,提供实习、工作机会或奖学金,为学生的职业生涯打开更多门路。 网络拓展: 比赛是结识同行业人才的好机会,可以帮助学生建立行业联系,这对于未来的职业发展非常重要。 奖金与荣誉: 许多比赛提供奖金或奖品,这不仅能给予学生经济上的奖励,还能增强其成就感和自信心。 荣誉证书或奖状可以证明学生的成就,对个人品牌建设有积极作用。 创新与研究: 参加比赛可以激发学生的创新思维,推动科研项目的开展,有时甚至能促成学术论文的发表。 个人成长: 在准备和参加比赛的过程中,学生将面临压力与挑战,这有助于培养良好的心理素质和抗压能力。 自我挑战和克服困难的经历对个人成长有着深远的影响。 综上所述,参加计算机领域的比赛对于学生来说是一个全面发展的平台,不仅可以提升专业技能,还能增强团队协作、沟通、解决问题的能力,并为未来的职业生涯奠定坚实的基础。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值