1.加入jar包:
commons-fileupload-1.2.2.jar
commons-io-2.0.1.jar
lperson.java中加属性,实现get ,set方法
private String photoPath;
2. 页面加:
1 <sf:form id="p" action="saveOrUpdate" 2 method="post" 3 modelAttribute="person" 4 enctype="multipart/form-data"> 5 6 <sf:hidden path="id"/> 7 name: <sf:input path="name"/><br> 8 age: <sf:input path="age"/><br> 9 photo: <input type="file" name="photo"/><br>
3 . 后台方法:
public JSONObject insert(Employee record, @RequestParam("photo") MultipartFile photo,
HttpServletRequest request) {
// 图片上传处
if (!ffile.isEmpty()) {
String dir = Commons.DIR; // 设定文件保存的目录
String orName = photo.getOriginalFilename();
int index = orName.lastIndexOf(Commons.DIAN);
String filename = record.getIdcardno() + orName.substring(index); // 文件名用上传的身份证号
try {
FileUtils.writeByteArrayToFile(new File(dir, filename),
photo.getBytes());
} catch (IOException e) {
log.error("upload fail:" + e.getMessage());
}
record.setPath(dir + "/" + filename); // 设置图片所在路径
log.info("upload success. " + filename);
}
...
}
4. 文件上传功能实现 spring-mvc.xml 配置文件上传解析器
1 <!-- 文件上传解析器 id 必须为multipartResolver --> 2 <bean id="multipartResolver" 3 class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 4 <property name="maxUploadSize" value=“10485760"/> 5 </bean> 6 7 maxUploadSize以字节为单位:10485760 =10M id名称必须这样写