Hướng dẫn upload file trong spring webmvc

2023-06-13 18:25:02

Hướng dẫn upload file trong spring webmvc

Bước 1: Tạo ứng dụng Dynamic Web 

Bước 2: Convert to maven project

Bước 3: Thêm các thư viện cho ứng dụng trong file pom.xml

Thêm các thư viện sau:

    • spring web mvc
    • common-io
    • commons-fileupload
    • jstl

 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>validateFormSpring</groupId>
  <artifactId>validateFormSpring</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <dependencies>
  <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.18</version>
</dependency>

  <!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
	<dependency>	
	    <groupId>javax.validation</groupId>
	    <artifactId>validation-api</artifactId>
	    <version>2.0.1.Final</version>
	</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.1.0.Final</version>
</dependency>
<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.5</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.11.0</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/jstl/jstl -->
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

  </dependencies> 
   <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.1</version>
        <configuration>
          <release>17</release>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.2.3</version>
      </plugin>
    </plugins>
  </build>
</project>

Bước 4: Cấu hình file web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>validateFormSpring</display-name>
<servlet> 

  	<servlet-name>validateFormSpring</servlet-name> 

  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 

  	<init-param> 

  		<param-name>contextConfigLocation</param-name> 

  		<param-value>/WEB-INF/config/spring-config.xml</param-value> 

  	</init-param> 

  </servlet> 

  <servlet-mapping> 

  	<servlet-name>validateFormSpring</servlet-name> 

  	<url-pattern>/</url-pattern> 

  </servlet-mapping> 
<filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

Bước 5: Tạo file cấu hình spring-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 

  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 
 xmlns:mvc="http://www.springframework.org/schema/mvc" 
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 

    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
    "> 

  <context:component-scan base-package="controllers" /> 
	<mvc:annotation-driven></mvc:annotation-driven>
	<context:annotation-config></context:annotation-config>
	<mvc:resources location="/uploads/" mapping="/uploads/**"></mvc:resources>
  <bean 

    class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 

    <property name="prefix"> 

      <value>/views/</value> 

    </property> 

    <property name="suffix"> 

      <value>.jsp</value> 

    </property> 

  </bean> 
	 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
</beans>
  • Chú ý: Tạo một thư mục uploads  trong WebContent để chứa các tài nguyên cho ứng dụng đó

 Bước 6: Tạo class entity Account

package entities;

import java.util.Date;

import javax.validation.constraints.Email;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Length;


public class Account {
	@NotEmpty(message = "fullname không rỗng nhé")
	private String fullName;
	@NotEmpty(message = "email không rỗng nhé")
	@Email(message = "email không đúng định dạng")
	private String email;
	

	@NotBlank(message = "password không rỗng nhé")
	@Email(message = "email không đúng định dạng")
	private String password;
	
	@NotEmpty(message = "email không rỗng nhé")
	@Pattern(message = "Không ddunsgd dịnh dạng",regexp = "^[a-zA-Z0-9]{3}")
	private String phone;
	@NotNull(message = "birthday không rỗng nhé")
	private Date birthday;
	private String imgName;
	
	public Account() {
		// TODO Auto-generated constructor stub
	}
	
	
	




	public Account(@NotEmpty(message = "fullname không rỗng nhé") String fullName,
			@NotEmpty(message = "email không rỗng nhé") @Email(message = "email không đúng định dạng") String email,
			@NotBlank(message = "password không rỗng nhé") @Email(message = "email không đúng định dạng") String password,
			@NotEmpty(message = "email không rỗng nhé") @Pattern(message = "Không ddunsgd dịnh dạng", regexp = "^[a-zA-Z0-9]{3}") String phone,
			@NotNull(message = "birthday không rỗng nhé") Date birthday, String imgName) {
		super();
		this.fullName = fullName;
		this.email = email;
		this.password = password;
		this.phone = phone;
		this.birthday = birthday;
		this.imgName = imgName;
	}







	public String getFullName() {
		return fullName;
	}

	public void setFullName(String fullName) {
		this.fullName = fullName;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	

	public String getImgName() {
		return imgName;
	}


	public void setImgName(String imgName) {
		this.imgName = imgName;
	}
}

Bước 7: Tạo trang add.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 <%@taglib prefix="f" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
</head>
<body>

<div class="container">
<div class="col-lg-6">
<f:form action="insertAccount" method="POST" modelAttribute="acc" enctype="multipart/form-data"ad>
 <div class="form-group">
    <label for="exampleInputEmail1">FullName</label>
    <f:input type="text" class="form-control" path="fullName"/>
    <f:errors cssClass="text-danger" path="fullName">
    	
    </f:errors>
  </div>
  <div class="form-group">
    <label for="exampleInputEmail1">Email address</label>
    <f:input type="text" class="form-control" path="email"/>
    <f:errors cssClass="text-danger" path="email">
    	
    </f:errors>
  </div>
  <div class="form-group">
    <label for="exampleInputPassword1">Password</label>
    <f:input type="password" class="form-control" path="password" />
    <f:errors cssClass="text-danger" path="password">
    	
    </f:errors>
  </div>
  <div class="form-group">
    <label for="exampleInputEmail1">Phone</label>
    <f:input type="text" class="form-control" path="phone"/>
     <f:errors cssClass="text-danger" path="phone">
    	
    </f:errors>
  </div>
  <div class="form-group">
    <label for="exampleInputEmail1">Birthday</label>
    <f:input type="date" class="form-control" path="birthday"/>
    <f:errors cssClass="text-danger" path="birthday">
    	
    </f:errors>
  </div>
  <input type="file" name="imageName"/>
  <button type="submit" class="btn btn-primary">Submit</button>
</f:form>
</div>
</div>
	
</body>
</html>

Bước 8: Tạo class CustomerController 

package controllers;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import entities.Account;

@Controller
public class AccountController {
	@InitBinder
    public void initBinder(WebDataBinder data) {
        SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
        s.setLenient(false);
        data.registerCustomEditor(Date.class, new CustomDateEditor(s, true));
    }
    

	@GetMapping({"/","/insertAccount"})
	public String addAccount(Model model) {
		Account account = new Account();
		model.addAttribute("acc", account);
		return "add";
	}
	
	@PostMapping("insertAccount")
	public String insertAccount(@Valid @ModelAttribute("acc") Account acc,BindingResult result, HttpSession session,@RequestParam("imageName")MultipartFile fileImage,Model model,HttpServletRequest request) {
		
		if(result.hasErrors()) {
			return "add";
		} else {
			//xu ly upload anh
			String path = request.getServletContext().getRealPath("uploads/images");
			File f = new File(path);
			
			File destination = new File(f.getAbsolutePath()+"/"+fileImage.getOriginalFilename());
			System.out.println(destination);
			if(!destination.exists()) {
				try {
					Files.write(destination.toPath(), fileImage.getBytes(), StandardOpenOption.CREATE);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			acc.setImgName(fileImage.getOriginalFilename());
			return "infor";
		}
	
	}
}

Bước 9: Tạo trang infor.jsp

hiển  thị hình ảnh 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<img alt="${acc.imgName}" src="<c:url value="uploads"/>/images/${acc.imgName}" width="200" height="200">
</body>
</html>

 

Bài viết liên quan

Ngày đăng : 2023-08-31 08:48:49
Spring MVC Custom Validation(Hướng dẫn validate file)

Spring MVC Custom Validation- Hướng dẫn validate file multipart file, custome anotation validate, validate file không rỗng , validate định dạng file.....

Read More
Ngày đăng : 2023-07-26 17:12:59
Hướng dẫn sử dụng i18n Internationalization(Quốc tế hóa) làm đa ngôn ngữ trong Spring MVC

Sử dụng i18n Internationalization(Quốc tế hóa) làm đa ngôn ngữ trong ứng dụng web với Spring MVC

Read More
Ngày đăng : 2023-07-20 17:17:45
Tải giao diện Admin LTE

Tải giao diện Admin LTE 2 bản rút gọn nhẹ làm trang quản trị cho ứng dụng web ...............

Read More
Ngày đăng : 2023-06-22 11:15:11
Hướng dẫn CRUD Spring WebMVC vs Hibernate phần 2 (Quản lý sản phẩm)

Hướng dẫn CRUD Spring WebMVC vs Hibernate phần 2 (Quản lý sản phẩm), CRUD có upload image và có quan hệ khóa ngoại

Read More
Ngày đăng : 2023-06-20 10:30:47
Hướng dẫn CRUD (Thêm sửa xóa) Spring WebMVC vs Hibernate

Hướng dẫn Thêm sửa xóa dữ liệu với spring webmvc sử dụng hibernate , trong bài viết này mình sử dụng database oracle

Read More
Ngày đăng : 2023-06-13 18:15:39
Hướng dẫn validate form trong Spring WebMVC

Hướng dẫn validate form trong springMVC sử dụng javax-validate

Read More
Ngày đăng : 2023-06-08 14:57:17
Tổng quan về Spring Framework và Spring MVC

Là một framework phát triển ứng dụng phổ biến nhất cho ứng dụng doanh nghiệp trong Java Là một nền tảng Java mã nguồn mở. Được viết đầu tiên bởi Rod Johnson và được phát hành lần đầu dưới phiên bản Apache 2.0 vào tháng 6 năm 2003

Read More