这两天想做一个上传图片的demo,但是参考了很多博客,依旧踩了很多坑,一方面也是自己的基础欠缺,首先先介绍我踩的2个坑
第一:File的构造方法
public static void main(String[] args) { String filePath ="D:\\upload" ; //保存图片的路径 String newFileName=UUID.randomUUID().toString(); File tagetFile = new File(filePath,newFileName); File tagetFile1 = new File(filePath+newFileName); System.out.println(tagetFile); System.out.println(tagetFile1); } 输出结果: D:\upload\d2d0c709-8889-4a76-8985-b81ce320de8a D:\uploadd2d0c709-8889-4a76-8985-b81ce320de8a
所以要注意File构造函数里面是拼字符串还是形成一个路径还是父路径拼子路径 这点要注意!
第二:在展示页面 的<img > 标签中:不能加上全包名${pageContext.request.ContextPath},加上就是错了
正确的写法是: <img src="/image/${user.img}">用户名:${user.username}
===================================================================================
下面是图片上传的流程,首先导入2个包
<!--上传图片相关--> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.2</version> </dependency>
在spring-mvc配置
<!--5.配置文件上传解析器-->
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="25000"></property>
</bean>
首先是注册界面:(我感觉应该添加一个拖拽的框框,用异步加载图片到这个框框上,这个待实现)
这里要注意的是:
method="post" enctype="multipart/form-data" 目的是多部份提交把表单形式按二进制格式提交,表单name是file
<div class="container"> <div class="row"> <div class="col-md-12"> <form action="${pageContext.request.contextPath}/user/imageUpload" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="Username">Username</label> <input type="test" class="form-control" id="Username" placeholder="Username" name="username"> </div> <div class="form-group"> <label for="exampleInputPassword1">Password</label> <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password" name="password"> </div> <div class="form-group"> <label for="birthday">birthday</label> <input type="date" class="form-control" id="birthday" placeholder="birthday" name="birthday"> </div> <div class="form-group"> <label for="file">File input</label> <input type="file" id="file" name="file" > </div> <div class="checkbox"> <label> <input type="checkbox"> Check me out </label> </div> <button type="submit" class="btn btn-default">Submit</button> </form> </div> </div> </div>
然后是实体类:User:这里注意我把 private MultipartFile file; 封装在实体类中,还有Date类型在SpringMVC中要加上注解不然不成功
package com.mkx_test.domain; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.web.multipart.MultipartFile; import java.util.Date; public class User { private int id; private String username; private String password; @DateTimeFormat(pattern = "yyyy-MM-dd") private Date birthday; private String img; private MultipartFile file; public String getImg() { return img; } public void setImg(String img) { this.img = img; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public MultipartFile getFile() { return file; } public void setFile(MultipartFile file) { this.file = file; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + ", birthday=" + birthday + ", img='" + img + '\'' + ", file=" + file + '}'; } }
Controller层
@Controller @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping("/imageUpload") public String imageUpload(User user , Model model, HttpServletRequest request) throws IOException { /** * 上传图片 */ String filePath ="D:\\upload" ; //保存图片的路径 String newFileName =null ; if(!user.getFile().isEmpty()){ //获取原始图片的拓展名 String originalFilename = user.getFile().getOriginalFilename();//v2-b8b4c3500d2f56d826d1eba7dd684c3c_720w.jpg //新的文件名称 newFileName=UUID.randomUUID().toString().replaceAll("-","")+originalFilename; System.out.println("newFileName"+newFileName);//0a1ffe50-d91e-4ef8-aa7c-6b353154af03v2-b8b4c3500d2f56d826d1eba7dd684c3c_720w.jpg //封装上传文件位置的全路径 //File tagetFile = new File(filePath,newFileName); //把本地文件上传到封装上传位置的全路径 user.getFile().transferTo(new File(filePath,newFileName)); } user.setImg(newFileName); //保存信息 userService.register(user); model.addAttribute("user",user); return "home"; }
数据库中:
图片文件的虚拟映射,因为图片实际上是保存在本地的磁盘中,而数据库只存了相对路径
展示页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <style> img{ width: 150px; height: 150px; } </style> </head> <body> <div> <img src="/image/${user.img}">用户名:${user.username} </div> </body> </html>