SpringMVC学习笔记(六) 文件上传

需要的两个jar包:
com.springsource.org.apache.commons.fileupload-1.2.0.jar、
com.springsource.org.apache.commons.io-1.4.0.jar、

web.xml

配置springmvc,url-pattern中写 *.do 、

spring-mvc.xml

除了配置使用注解的包和视图解析器之外、要支持文件上传需要加一个bean、

<bean id="multipartResolver"
       class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="defaultEncoding" value="UTF-8"/>  
    <property name="maxUploadSize" value="10000000"/>    <!-- 最大上传字节 10M -->
</bean>

FileUploadController

//单文件上传、
@RequestMapping("/upload")
public String uploadFile(@RequestParam("file1") MultipartFile file1,HttpServletRequest request)throws Exception{            //前端有个name=file1的上传控件
	String filePath=request.getServletContext().getRealPath("/");	//取项目路径
        //查看此处输出的路径、在开发环境中,Tomcat是作为eclipse的一个插件、上传到插件的tmp目录去了、但是取的时候不会有影响、
	System.out.println(filePath);
		//把一个文件输出到指定目录
	file1.transferTo(new File(filePath+"upload/"+file1.getOriginalFilename()));
	return "redirect:success.html";
}

//多文件上传、用数组接收
@RequestMapping("/upload2")
public String uploadFiles(@RequestParam("file") MultipartFile[] files,HttpServletRequest request)throws Exception{
	String filePath=request.getServletContext().getRealPath("/");
	System.out.println(filePath);
	for(MultipartFile file:files){	//遍历files数组
		//实际开发中文件需要重新命名 比如当前日期的字符串(自己写工具类),此处是得到上传时的文件名
		file.transferTo(new File(filePath+"upload/"+file.getOriginalFilename()));			
	}
	return "redirect:success.html";
}

index.html

<!-- —————————单文件上传————————— -->
<form action="upload.do" method="post" enctype="multipart/form-data"><!-- enctype="multipart/form-data上传文件 -->

<input type="file" name="file1"/>

<!-- —————————多文件上传————————— -->
<form action="upload2.do" method="post" enctype="multipart/form-data">

<input type="file" name="file"/>    <!-- 将该语句复制多个到table中 -->
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值