重点
首先项目要配置到Tomcat中才能实现图片或者其他文件上传到服务器(Tomcat)中
具体配置点击
首先springmvc-servlet.xml中配置
<!-- 单文件上传 配置MultiparResolver用户上传文件,使用spring-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxInMemorySize" value="5000000"/>
<property name="defaultEncoding" value="UTF-8"/>
</bean>
form表单处理
<form action="hr/filterSc" method="post" enctype="multipart/form-data">
<label>文件上传</label>
<input type="file" name="file">
<input type="submit" value="提交">
</form>
Controller中处理
@RequestMapping(value="filterSc",method = RequestMethod.POST)
public String filterSc(@RequestParam(value = "file",required = true) MultipartFile file,HttpServletRequest request) throws IllegalStateException, IOException {
// uploads文件夹位置
String rootPath = request.getServletContext().getRealPath("resources/uploads/");
// 原始名称
System.out.println(rootPath);
// 原始名称
String originalFileName = file.getOriginalFilename();
// 新文件名
String newFileName = "sliver" + originalFileName.substring(originalFileName.lastIndexOf("."));
// 新文件
File newFile = new File(rootPath + File.separator + newFileName);
// 判断目标文件所在目录是否存在
if(!newFile.getParentFile().exists()) {
// 如果目标文件所在的目录不存在,则创建父目录
newFile.getParentFile().mkdirs();
// 将内存中的数据写入磁盘
file.transferTo(newFile);
}
return "filterSc";
}
测试
选择图片
提交
在自己的tomcat中项目中,我的路径E:\Tomcat\apache-tomcat-7.0.94\webapps\HrWebTwo\resources\uploads\sliver.jpg
sliver.jpg
Over!!!