struts2头像上传练习及其注意事项
2016-03-29 10:09
471 查看
1.jsp页面
注意:form表单要加 enctype="multipart/form-data" ,头像的input要使用file类型
2.action控制器
注意: private File headImg; 的名字要与jsp页面传来的名字(name)一致
出现过的问题:
<form id="form" name="form" action="${basePath}nsfw/user_add.action" method="post" enctype="multipart/form-data"> ... <tr> <td class="tdBg" width="200px">头像:</td> <td> <input type="file" name="headImg"/> </td> </tr>
注意:form表单要加 enctype="multipart/form-data" ,头像的input要使用file类型
2.action控制器
//头像上传 private File headImg; private String headImgContentType; private String headImgFileName; ... //保存新增 public String add(){ try { if(user != null){ System.out.println(headImg); //处理头像 if(headImg != null){ //1.保存头像到upload/user //获取保存路径的绝对地址 String filePath = ServletActionContext.getServletContext().getRealPath("/upload/user"); System.out.println(filePath); String fileName = UUID.randomUUID().toString().replaceAll("-", "")+headImgFileName.substring(headImgFileName.lastIndexOf(".")); //复制文件 FileUtils.copyFile(headImg, new File(filePath, fileName)); //2、设置用户头像路径 user.setHeadImg("user/" + fileName); } userService.save(user); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return "list"; }
注意: private File headImg; 的名字要与jsp页面传来的名字(name)一致
出现过的问题:
String filePath = ServletActionContext.getServletContext().getRealPath("/upload/user");这行代码的 "/upload/user" 写成"upload/user" 时,不会把文件上传到服务器。
相关文章推荐
- struts2中Action的学习
- Ubuntu下设置Eclipse支持GBK和GB2312
- 深入Java集合学习之HashMap的实现原理详解
- java Properties异常:Malformed \uxxxx encoding.
- Spring AOP 详解
- java基础知识总结3
- java-poi处理excell
- JAVA自动化测试中多数据源的切换
- Java中的Map汇总——思维导图
- java解析xml的4种经典方法
- Spring实现的动态文件下载(以Excel导出为例)
- java 内存溢出解决
- Spring实现AOP的4种方式
- Java 之NIO(三) - FileLock
- java基础知识总结2
- java基础知识总结1
- 通过Java字节码发现有趣的内幕之初始化篇(下)
- 通过Java字节码发现有趣的内幕之String篇(中)
- JAVA多线程——死锁分析
- 浅析Spring 事务(二十) 走进spring事务