Spring MVC – Code ví dụ Spring MVC Upload File

Spring MVC – Code ví dụ Spring MVC Upload File

(Xem thêm: Spring MVC Upload File kết hợp Progress Bar (JQuery, Bootstrap))

Spring MVC Upload File

Hướng dẫn tạo một project ví dụ upload file trong Spring MVC. Đính kèm một số thông tin khi upload fileHướng dẫn tạo một project ví dụ upload file trong Spring MVC. Đính kèm một số thông tin khi upload fileHướng dẫn tạo một project ví dụ upload file trong Spring MVC. Đính kèm một số thông tin khi upload file

 Spring MVC - Code ví dụ Spring MVC Upload File

Thư viện sử dụng:

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>stackjava.com</groupId>
  <artifactId>SpringMVCUploadFile</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.0.2.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.3</version>
    </dependency>


  </dependencies>
</project>

Thư viện commons-fileupload được dùng để xử lý file trong form upload lên server

File Spring Config

<?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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
    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">

  <context:component-scan base-package="stackjava.com.springmvc" />

  <mvc:annotation-driven />
  <mvc:resources mapping="/resources/**" location="/resources/bootstrap/"
    cache-period="31556926" />

  <bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
      <value>/WEB-INF/views/jsp/</value>
    </property>
    <property name="suffix">
      <value>.jsp</value>
    </property>
  </bean>
  <bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="268435456" />
  </bean>

</beans>

org.springframework.web.multipart.commons.CommonsMultipartResolver thực hiện cài đặt lại Apache Common Upload

thuộc tính maxUploadSize chỉ dẫn kích thước tối đa mà file được upload.

(lưu ý một số trường hợp bạn cần phải thay đổi kích thước file cho phép upload trên server, ví dụ server tomcat mặc định kích thước file được upload lớn nhất khoảng mấy chục Mb gì đó)

Class Model

package stackjava.com.springmvc.model;

import java.io.Serializable;

import org.springframework.web.multipart.MultipartFile;

public class MyFile implements Serializable {
  private static final long serialVersionUID = 1L;
  private MultipartFile multipartFile;
  private String description;

  //getter - setter

}

MultipartFile là đối tượng file được upload lên

Ở đây ngoài file còn có thể có một số thông tin được submit cùng nên mình thêm thuộc tính description để ví dụ

Controller

package stackjava.com.springmvc.controller;

import java.io.File;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import stackjava.com.springmvc.model.MyFile;

@Controller
public class BaseController {

  @RequestMapping("/")
  public String index(Model model) {
    model.addAttribute("myFile", new MyFile());

    return "index";
  }

  @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
  public String uploadFile(MyFile myFile, Model model) {
    model.addAttribute("message", "upload success");
    model.addAttribute("description", myFile.getDescription());
    
    try {
      MultipartFile multipartFile = myFile.getMultipartFile();
      String fileName = multipartFile.getOriginalFilename();
      File file = new File("D:/files", fileName);
      multipartFile.transferTo(file);
    } catch (Exception e) {
      e.printStackTrace();
      model.addAttribute("message", "upload failed");
    }
    return "result";
  }

}

File sau khi được upload sẽ được lưu vào folder D:/files

File view:

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>index</title>
</head>
<body>
  <form:form method="POST" action="uploadFile" enctype="multipart/form-data" modelAttribute="myFile">
    File: <input type="file" name="multipartFile" /> <br /> <br/>
    Description: <form:input path="description"/> <br />
    <input type="submit" value="Submit" />
  </form:form>
</body>
</html>
<html>
<head>
<title>index</title>
</head>
<body>
  <h1>${message}</h1>
  <br/>
  description: ${description}
</body>
</html>

Lưu ý:

File bạn upload phải có kích thước nhỏ hơn kích thước lớn nhất mà server cho phép, ví dụ mình chạy trên server tomcat thì cần phải điều chỉnh kích thước lớn nhất mà tomcat cho phép:

Cấu hình giới hạn kích thước file upload cho Tomcat

Demo:

Spring MVC – Phần 11: Upload File + Sử dụng Progress Bar trong Spring MVC

Spring MVC – Phần 11: Upload File + Sử dụng Progress Bar trong Spring MVC

Spring MVC – Phần 11: Upload File + Sử dụng Progress Bar trong Spring MVC

Spring MVC – Code ví dụ Spring MVC Upload File stackjava.com

 

Okay, Done!

Download code ví dụ trên tại đây

 

References:

https://commons.apache.org/proper/commons-fileupload/

stackjava.com