MVC——12 SpringMVC的文件上传

SpringMVC的文件上传

1.基于 apache 的 commons-fileupload.jar 完成文件上传

2.MultipartResovler 作用

  1. 把客户端上传的文件流转换成 MutipartFile 封装类
  2. 通过 MutipartFile 封装类获取到文件流

3.表单数据类型分类

  1. 在form 标签 的 enctype 属性控制表单类型
  2. 默认值 application/x-www-form-urlencoded,普通表单数据(少量文字信息)
  3. text/plain 大文字量时使用的类型.邮件,论文
  4. multipart/form-data 表单中包含二进制文件内容.

4.实现步骤:

  1. 导入 springmvc 包和 apache 文件上传 commons-fileupload 和
    commons-io 两个 jar
  2. 编写 JSP 页面
<form action="upload" enctype="multipart/form-data" method="post">
姓名:<input type="text" name="name"/><br/> 
文件:<input type="file" name="file"/><br/> 
<input type="submit" value=" 提 交 "/> </form>
  1. 配置 springmvc.xml
<!-- MultipartResovler 解析器 --> 
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.Comm onsMultipartResolver"> 
<property name="maxUploadSize" value="50"></property> 
</bean>
<!-- 异常解析器 --> 
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.Simple MappingExceptionResolver"> 
	<property name="exceptionMappings"> 
	<props> 
	<prop key="org.springframework.web.multipart.MaxUploadSizeE xceededException">/error.jsp</prop> 
	</props> 
	</property> 
</bean>
  1. 编写控制器类
    注:MultipartFile 对象名必须和 inputtype=”file”/ 标签 的 name 属性值相同
@RequestMapping("upload") 
public String upload(MultipartFile file,String name) throws IOException{ 
String fileName = file.getOriginalFilename(); 
String suffix = fileName.substring(fileName.lastIndexOf("."));
//判断上传文件类型 
if(suffix.equalsIgnoreCase(".png")){ 
String uuid = UUID.randomUUID().toString();
FileUtils.copyInputStreamToFile(file.getInputStream (), new File("E:/"+uuid+suffix));
return "/index.jsp"; 
}
	else{ 
	return "error.jsp"; 
	} 
}
发布了167 篇原创文章 · 获赞 15 · 访问量 6167

猜你喜欢

转载自blog.csdn.net/Re_view/article/details/100584577
今日推荐