SpringMVC_05_文件上传

分为单文件上传和多文件上传。

直接通过例子介绍:

1.需要在spring-mvc.xml引入beans:

<bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="UTF-8"/>  
	    <property name="maxUploadSize" value="10000000"/>
	</bean>

默认编码方式:utf-8

上传最大大小:10000000

 2.引入相关jar包

3.Controller:

	@RequestMapping("/upload")
	public String uploadFile(@RequestParam("file") MultipartFile file,HttpServletRequest request) throws Exception{
		String filePath = request.getServletContext().getRealPath("/");
		System.out.println(filePath);
		file.transferTo(new File(filePath+"upload/"+file.getOriginalFilename()));
		return "redirect:success.html";
	}

把文件下载到根目录下的upload文件夹下,文件名字用之前文件名。

4.界面:

<form action="upload.do" method="post" enctype="multipart/form-data">
<table>
	<tr>
		<th colspan="2">文件上传</th>
	</tr>
	<tr>
		<td>文件一</td>
		<td><input type="file" name="file"></td>
	</tr>
	<tr>
		<th colspan="2"><input type="submit" value="上传"></th>
	</tr>
</table>
</form>

enctype="multipart/form-data"要有,一定使用post

扫描二维码关注公众号,回复: 2811222 查看本文章

测试:

但是你会发现在Eclipse下的项目的upload却找不到1.txt,看一下文件路径:

C:\Users\sherlock\Documents\gao jishu\Eclipse_Photon\workspace_springmvc\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SpringMvc04\

是在eclipse为你生成的目录下,但你通过请求是可以访问到。

下面说,多文件上传:

	@RequestMapping("/uploads")
	public String uploadFiles(@RequestParam("file") MultipartFile[] files,HttpServletRequest request) throws Exception{
		String filePath = request.getServletContext().getRealPath("/");
		System.out.println(filePath);
		for(MultipartFile file:files) {	
			file.transferTo(new File(filePath+"upload/"+file.getOriginalFilename()));
		}
		return "redirect:success.html";
	}
}

就是把参数改成数组即可。

测试:

猜你喜欢

转载自blog.csdn.net/qq_27163329/article/details/81702666