SSM环境下的Java上传文件
- 通过MultipartFile类上传文件。
- 步骤:
- a.SpringMvc中加入配置
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--设置上传最大尺寸为1MB-->
<property name="maxUploadSize" value="1048576"/>
<property name="maxInMemorySize" value="5242880"/>
<property name="defaultEncoding" value="UTF-8"/>
<property name="resolveLazily" value="true"/>
</bean>
<--文件超过大小后异常的处理(此时出现的异常不会到Controller中)-->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!-- 绕过了前端的大小限制,跳转到error.jsp页面 -->
<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">redirect:/error.jsp
</props>
</property>
</bean>
-
b.
@RequestMapping(value = "/image", method=RequestMethod.POST)
public Result uploadImage(HttpServletRequest request, @RequestParam("file")MultipartFile file){//file参数为web前台的name属性值
String name = file.getName();
System.out.println(name);//得到的是file
String originalFilename = file.getOriginalFilename();
System.out.println(originalFilename);//得到上传的文件名全称
File file2 = new File("E:\1234.txt");
try {
file.transferTo(file2);//将文件保存到硬盘
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
result.setState(1);
return result;
}