================== Spring MVC上传文件 ================== 1 前端 表单提交方式必须为POST。 表单enctype属性为multipart/form-data。 /src/main/webapp/addBook.jsp: ... ...
...
... ... 2 实体类 自动填值的属性,其名称必须与表单项的name严格一致,不一致者手动填值。 /src/main/java/cn/tedu/springfile/pojo/Book.java: public class Book { private int id; private String name; // <-Setter- form.name private String author; // <-Setter- form.author private double price; // <-Setter- form.price private String cover; public Book() { } public Book(int id, String name, String author, double price, String cover) { this.id = id; this.name = name; this.author = author; this.price = price; this.cover = cover; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String getCover() { return cover; } public void setCover(String cover) { this.cover = cover; } @Override public String toString() { return "Book{" + "id=" + id + ", name='" + name + '\'' + ", author='" + author + '\'' + ", price=" + price + ", cover='" + cover + '\'' + '}'; } } 3 控制器 enctype属性为multipart/form-data的表单数据,如何传入控制器方法? 前端上传的文件如何接收? - 添加依赖 /pom.xml: commons-io commons-io 2.4 commons-fileupload commons-fileupload 1.4 - 添加组件 /src/main/resources/spring-servlet.xml: ... ... - 接收文件 在/src/main/webapp/images目录下随便放个文件,以使该目录被部署。 /src/main/java/cn/tedu/springfile/controllers/BookController.java: ... public class BookController { ... public String addBook(Book book, MultipartFile image, HttpServletRequest request) throws IOException { ... // 原始文件名 String originalFilename = image.getOriginalFilename(); // 文件名后缀 String suffix = originalFilename.substring( originalFilename.lastIndexOf(".")); // 文件名 String filename = System.currentTimeMillis() + suffix; // 目录名 String dir = request.getServletContext().getRealPath("images"); // 存储路径 String filepath = dir + "/" + filename; // 保存文件 image.transferTo(new File(filepath)); // 访问路径 String cover = "images/" + filename; book.setCover(cover); System.out.println("控制器> 封面:" + book.getCover()); ... } ... } 例程:SpringFile