Upload File trong Spring MVC

Tải tập tin (Upload File) là chức năng phổ biến mà trong bất kỳ ứng dụng Web cũng cần, bài hướng dẫn sau đây sẽ trình bày Upload File trong Spring MVC.

Trong Spring MVC cung cấp hỗ trợ để tải lên các tệp bằng cách tích hợp thư viện Commons FileUpload của Apache. Để thực hiện chức năng tải tập tin lên máy chủ trong Spring MVC dễ dàng, bạn thực hiện theo các bước sau đây.

Yêu cầu thực hiện:

Spring MVC
JSTL
Netbeans IDE

Bước 1: Thêm thư viện commons-fileupload, commons-io vào dự án. Tiếp theo tạo lớp MyFiles.java chứa thông tin tập tin như tên tập tin, dung lượng…

package com.teamvietdev.model;

/**
*
* @author TVD
*/
public class MyFiles {

private long fileId;
private String fileName;
private String filePath;
private String fileOriginalFilename;
private String fileContentType;
private long fileSize;
private String fileDate;

public long getFileId() {
return fileId;
}

public void setFileId(long fileId) {
this.fileId = fileId;
}

public String getFileName() {
return fileName;
}

public void setFileName(String fileName) {
this.fileName = fileName;
}

public String getFilePath() {
return filePath;
}

public void setFilePath(String filePath) {
this.filePath = filePath;
}

public String getFileOriginalFilename() {
return fileOriginalFilename;
}

public void setFileOriginalFilename(String fileOriginalFilename) {
this.fileOriginalFilename = fileOriginalFilename;
}

public String getFileContentType() {
return fileContentType;
}

public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}

public long getFileSize() {
return fileSize;
}

public void setFileSize(long fileSize) {
this.fileSize = fileSize;
}

public String getFileDate() {
return fileDate;
}

public void setFileDate(String fileDate) {
this.fileDate = fileDate;
}

}

Trong tập tin dispatcher-servlet.xml bạn cần thêm đoạn mã:

<bean id=”multipartResolver” class=”org.springframework.web.multipart.commons.CommonsMultipartResolver”>
<property name=”maxUploadSize” value=”268435456″ />
</bean>

Bước 2: Tạo lớp UploadController.java nhằm xử lý hiển thị danh sách các tập tin đã tải lên, xử lý yêu cầu Upload File trong Spring MVC.

package com.teamvietdev.controller;

import com.teamvietdev.model.MyFiles;
import java.io.File;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

/**
*
* @author TVD
*/
@Controller
@RequestMapping(value = “files”)
public class UploadController {

private static List<MyFiles> listFiles = null;

public UploadController() {
this.listFiles = new ArrayList<>();
}

@RequestMapping(value = “list.html”, method = RequestMethod.GET)
public String uploadList(ModelMap modelMap) {
modelMap.put(“listFiles”, listFiles);
return “jsp/upload_list”;
}

@RequestMapping(value = “uploadFile.html”, method = RequestMethod.GET)
public String uploadForm(ModelMap modelMap) {
return “jsp/upload_file”;
}

@RequestMapping(value = “uploadMultiFile.html”, method = RequestMethod.GET)
public String uploadMulForm(ModelMap mm) {
return “jsp/upload_multiple_file”;
}

@RequestMapping(value = “uploadFile.html”, method = RequestMethod.POST)
public String uploadFile(ModelMap modelMap, @RequestParam(“file”) MultipartFile file, HttpServletRequest request) {
try {
String path = request.getSession().getServletContext().getRealPath(“/”) + “resources/uploads/”;

Timestamp tnow = new Timestamp(new Date().getTime());
MyFiles f = new MyFiles();
f.setFileId(tnow.getTime());
f.setFileName(file.getName());
f.setFileName(file.getOriginalFilename());
f.setFileDate(file.getContentType());
f.setFileSize(file.getSize());
f.setFileDate(tnow.toString());
listFiles.add(f);
// FileUtils.forceMkdir(new File(“D:/uploads/”));
// File upload = new File(“D:/uploads/” + file.getOriginalFilename());
// file.transferTo(upload);
FileUtils.forceMkdir(new File(path));
File upload = new File(path + file.getOriginalFilename());
file.transferTo(upload);
f.setFilePath(path + file.getOriginalFilename());
} catch (Exception ex) {
ex.printStackTrace();
}
modelMap.put(“listFiles”, listFiles);
return “jsp/upload_list”;
}

@RequestMapping(value = “uploadMultiFile.html”, method = RequestMethod.POST)
public String uploadMultiFile(ModelMap modelMap, @RequestParam(“files”) MultipartFile[] files, HttpServletRequest request) {
try {
String path = request.getSession().getServletContext().getRealPath(“/”) + “resources/uploads/”;
for (MultipartFile file : files) {
Timestamp tnow = new Timestamp(new Date().getTime());
MyFiles f = new MyFiles();
f.setFileId(tnow.getTime());
f.setFileName(file.getName());
f.setFileName(file.getOriginalFilename());
f.setFileDate(file.getContentType());
f.setFileSize(file.getSize());
f.setFileDate(tnow.toString());
listFiles.add(f);
FileUtils.forceMkdir(new File(path));
File upload = new File(path + file.getOriginalFilename());
file.transferTo(upload);
f.setFilePath(path + file.getOriginalFilename());
}
} catch (Exception ex) {
ex.printStackTrace();
}
modelMap.put(“listFiles”, listFiles);
return “jsp/upload_list”;
}

}

Có thể lưu trữ tập tin trực tiếp trên ổ đĩa hoặc là bạn lưu trong thư mục của dự án, như ví dụ trên thì bạn tìm thấy tập tin sau khi tải lên sẽ nằm trong thư mục ..\UploadFiles\build\web\resources\uploads\

Trang upload_list.jsp hiển thị danh sách tập tin đã Upload File:

<%–
Document : upload_list
Created on : 10-Dec-2018, 8:58:33 PM
Author : TVD
–%>

<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<%@taglib uri=”http://java.sun.com/jsp/jstl/core” prefix=”c”%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>Upload List</title>

<link href=”//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css” rel=”stylesheet” id=”bootstrap-css”>
<script src=”//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js”></script>
<script src=”//code.jquery.com/jquery-1.11.1.min.js”></script>

</head>
<body>

<br />
<div class=”container”>
<div class=”row”>
<div class=”col col-xs-6″>
<h4>Upload List</h4>
[<a href=”${pageContext.request.contextPath}/files/uploadFile.html”>Upload File</a>] |
[<a href=”${pageContext.request.contextPath}/files/uploadMultiFile.html”>Upload Multiple File</a>]
</div>
<div class=”col col-xs-6 text-right”>
</div>
</div>
<div class=”clearfix”></div>
<div class=”row”>
<div class=”col-md-12″><br />
<div class=”table-responsive”>
<table id=”mytable” class=”table table-bordred table-striped”>
<thead>
<th>FileName</th>
<th>OriginalFilename</th>
<th>ContentType</th>
<th>Size</th>
<th>Date</th>
</thead>
<tbody>
<c:forEach var=”item” items=”${listFiles}”>
<tr>
<td><a href=”${item.filePath}”>${item.fileName}</a></td>
<td>${item.fileOriginalFilename}</td>
<td>${item.fileContentType}</td>
<td>${item.fileSize}</td>
<td>${item.fileDate}</td>
</tr>
</c:forEach>
</tbody>
</table>
<div class=”clearfix”></div>
</div>
</div>
</div>
</div>

</body>
</html>

Trang upload_file.jsp hiển thị giao diện người dùng chọn Upload File trong Spring MVC:

<%–
Document : upload_file
Created on : 10-Dec-2018, 8:58:48 PM
Author : TVD
–%>

<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<%@taglib uri=”http://www.springframework.org/tags/form” prefix=”form”%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>Upload Form</title>
</head>
<body>

<form method=”POST” action=”${pageContext.request.contextPath}/files/uploadFile.html”
enctype=”multipart/form-data”>
<table>
<tr>
<td>Select a file to upload</td>
<td><input type=”file” name=”file” /></td>
</tr>
<tr>
<td><input type=”submit” value=”Submit” /></td>
</tr>
</table>
</form>

</body>
</html>

Trang upload_multiple_file.jsp hiển thị giao diện người dùng chọn tải nhiều tập tin cùng lúc trong Spring MVC:

<%–
Document : upload_multiple_file
Created on : 10-Dec-2018, 9:32:16 PM
Author : TVD
–%>

<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>Upload Form</title>

<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js”></script>
<script>
$(document).ready(function () {
$(‘#addFile’).click(function () {
$(‘#fileTable’).append(
‘<tr><td>Select a file to upload</td><td>’ +
‘ <input type=”file” name=”files” />’ +
‘</td></tr>’);
});
});
</script>

</head>
<body>

<br/>
<input id=”addFile” type=”button” value=”Add File” />
<form method=”POST” action=”${pageContext.request.contextPath}/files/uploadMultiFile.html”
enctype=”multipart/form-data”>
<table id=”fileTable”>
<tr>
<td>Select a file to upload</td>
<td><input type=”file” name=”files” /></td>
</tr>
<tr>
<td>Select a file to upload</td>
<td><input type=”file” name=”files” /></td>
</tr>
</table>
<input type=”submit” value=”Submit” />
</form>

</body>
</html>

Lưu ý cần đặt thuộc tính enctype=”multipart/form-data”  trong thẻ <form>.

Kết quả sau khi chạy ví dụ trên:

Giao diện hiển thị danh sách tập tin đã Upload:

Giao diện hiển thị danh sách tập tin đã Upload:

Upload File trong Spring MVC

Giao diện hiển thị biểu mẫu Upload File:

Upload File trong Spring MVC

Tải mã nguồn tại đây:

Lời kết: Trong thời gian tới Team Việt Dev sẽ tiếp tục chia sẻ thêm nhiều bài viết trong loạt bài hướng dẫn xây dựng web bán hàng bằng Spring MVC… miễn phí đến bạn đọc, các bạn nhớ theo dõi kênh để có được những chia sẻ mới nhất.

(Tác giả: Team Việt Dev)

Bình luận