基于ssm的上传图片
原创地址:http://blog.****.net/qq_33764491/article/details/77440180
第一次接触上传图片,自己还是很头疼的。大佬的帮助和网上的资料着实帮了我不少的忙~~所以,下面是我实现这个功能的思路。
用户注册时,需要上传图片(头像),这是该功能的背景。在实现之前,需要导入两个jar包:commons-fileupload-1.3.1和commons-io-2.4。
首先是jsp页面:
- <form action="file/upload.action" method="post" enctype="multipart/form-data">
- <label>用户名:</label><input type="text" name="name"><br>
- <label>密码:</label><input type="password" name="pwd"><br>
- <label>上传头像:</label><input type="file" name="file"><br>
- <input type="submit">
- </form>
需要注意的是,一定要写 enctype="multipart/form-data",否则springmvc就会解析失败。这个的作用就是将form表单的数据以二进制的方式传输。
配置springmvc.xml:
- <!-- 上传文件 -->
- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
- <property name="defaultEncoding" value="utf-8"/>
- <!-- 最大内存大小 -->
- <property name="maxInMemorySize" value="10240"/>
- <!-- 最大文件大小,-1为不限制大小 -->
- <property name="maxUploadSize" value="-1"/>
- </bean>
po和mapper我是利用****自动生成的,所以不再书写。需要注意的是:我将MultipartFile定义在实体类中。
- public class User {
- private Integer id;
- private String name;
- private String pwd;
- private String image;
- private MultipartFile file;
- @Controller
- @RequestMapping("/file")
- public class UserController {
- @Autowired
- IUserService userService;
- @RequestMapping("/upload")
- public String upload(User user,HttpServletRequest request,Model model) throws Exception{
- System.out.println(request.getParameter("name"));
- //保存数据库的路径
- String sqlPath = null;
- //定义文件保存的本地路径
- String localPath="D:\\File\\";
- //定义 文件名
- String filename=null;
- if(!user.getFile().isEmpty()){
- //生成uuid作为文件名称
- String uuid = UUID.randomUUID().toString().replaceAll("-","");
- //获得文件类型(可以判断如果不是图片,禁止上传)
- String contentType=user.getFile().getContentType();
- //获得文件后缀名
- String suffixName=contentType.substring(contentType.indexOf("/")+1);
- //得到 文件名
- filename=uuid+"."+suffixName;
- System.out.println(filename);
- //文件保存路径
- user.getFile().transferTo(new File(localPath+filename));
- }
- //把图片的相对路径保存至数据库
- sqlPath = "/images/"+filename;
- System.out.println(sqlPath);
- user.setImage(sqlPath);
- userService.addUser(user);
- model.addAttribute("user", user);
- return "MyJsp";
- }
Apache虚拟目录的设置:
在Apache的server.xml 下的<host></host>标签中,添加即可:
<Context docBase="D:\File" path="/images" reloadable="false"/>
MyJsp:
- <h3>显示图片</h3>
- <img src="${basePath}${user.image}">用户名:${user.name}
- <hr>
实现结果:
—————————————————————————————————————————————————————————————————————————————9.14更新+改进
注意这个坑,如果你用了逆向的方法selective,进行更新时,会出现无法更新成功的问题,原因就是之前写的是" ",而真正应该是null !
//把图片的相对路径保存至数据库
sqlPath = filename;
if(sqlPath!=null){
user.setUlogo(sqlPath);
}
在页面这样实现<img src="/images/${pacth}">