Java 文件上传练习案例:限制上传文件大小
Java 文件上传练习案例:限制上传文件大小
本案例基于参考案例 ch4.5_fileUpload(文件上传)进行扩展,实现文件上传功能,并限制上传文件的大小。
需求:
- 创建 Web 项目
ch4.5ex_uploadLimited,并将案例素材中的网页文件index.jsp和fileUpload.jsp复制到目录src/main/webapp,将 2 个 jar 包commons-fileupload-1.4.jar和commons-io-2.5.jar复制粘贴到目录src/main/webapp/WEB-INF/lib。 - 在文件选择页
index.jsp中,含有一个文本框和文件域,文本框的默认值为zhangsan或自己姓名的全拼。 - 在
fileUpload.jsp页中,修改和补充代码,实现根据文本框输入的内容,创建文件存放目录,如uploadFolder/zhangsan。 - 实现上传文件到该存放目录,并显示相关信息。
- 如果上传的文件大小超过 2MB,则不保存,并显示提示信息。
- 可选功能:获取上传文件的扩展名,如果上传的是 jsp 文件,则给出不许上传的提示;如果上传的是图片文件,则在页面上显示该图片,设置图片的最大宽度和最大高度都为 300px,且保持图片比例不变。
index.jsp 代码:
<%@ page language='java' contentType='text/html; charset=UTF-8'
pageEncoding='UTF-8'%>
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>上传文件</title>
<style>
.container {
width: 300px;
margin: auto;
margin-top: 50px;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 5px;
}
input[type='text'], input[type='file'] {
width: 100%;
padding: 8px;
border-radius: 5px;
border: 1px solid #ccc;
box-sizing: border-box;
}
input[type='submit'] {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
input[type='submit']:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<div class='container'>
<form action='fileUpload.jsp' method='post' enctype='multipart/form-data'>
<div class='form-group'>
<label>文件夹名称:</label>
<input type='text' name='folderName' value='zhangsan' required>
</div>
<div class='form-group'>
<label>选择文件:</label>
<input type='file' name='file' required>
</div>
<input type='submit' value='上传'>
</form>
</div>
</body>
</html>
fileUpload.jsp 代码:
<%@ page language='java' contentType='text/html; charset=UTF-8'
pageEncoding='UTF-8'%>
<%@ page import='java.io.*, java.util.*, org.apache.commons.fileupload.*, org.apache.commons.fileupload.disk.*, org.apache.commons.fileupload.servlet.*' %>
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>文件上传</title>
<style>
.container {
width: 300px;
margin: auto;
margin-top: 50px;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 5px;
}
input[type='text'], input[type='file'] {
width: 100%;
padding: 8px;
border-radius: 5px;
border: 1px solid #ccc;
box-sizing: border-box;
}
input[type='submit'] {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
input[type='submit']:hover {
background-color: #45a049;
}
.errorMsg {
color: #f00;
font-size: 12px;
}
.successMsg {
color: #0c0;
font-size: 14px;
font-weight: bold;
}
.imgPreview {
max-width: 300px;
max-height: 300px;
}
</style>
</head>
<body>
<div class='container'>
<%
String folderName = request.getParameter('folderName');
String filePath = 'uploadFolder/' + folderName;
boolean success = (new File(filePath)).mkdirs();
if (success) {
String fileName = '';
String filePathName = '';
String errorMsg = '';
boolean fileSaved = false;
boolean fileSizeLimited = false;
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(1024 * 1024 * 2); // 限制文件大小不超过2MB
try {
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
if (!item.isFormField()) {
fileName = item.getName();
long fileSize = item.getSize();
if (fileSize > 0 && fileSize <= upload.getSizeMax()) {
filePathName = filePath + '/' + fileName;
File uploadedFile = new File(filePathName);
item.write(uploadedFile);
fileSaved = true;
} else {
fileSizeLimited = true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
errorMsg = '上传文件出错,请重新上传!';
}
if (fileSaved) {
String successMsg = '文件上传成功!';
int index = fileName.lastIndexOf('.');
if (index > 0) {
String nameExt = fileName.substring(index + 1).toLowerCase();
if (nameExt.equals('jsp')) {
errorMsg = '不允许上传jsp文件!';
fileSaved = false;
} else if (nameExt.equals('jpg') || nameExt.equals('jpeg') || nameExt.equals('png') || nameExt.equals('gif') || nameExt.equals('bmp')) {
out.print('<p class='successMsg'>' + successMsg + '</p>');
out.print('<img class='imgPreview' src='' + filePathName + ''>');
} else {
out.print('<p class='successMsg'>' + successMsg + '</p>');
}
} else {
out.print('<p class='successMsg'>' + successMsg + '</p>');
}
} else {
if (fileSizeLimited) {
errorMsg = '上传文件大小超过限制(2MB)!';
} else if (errorMsg.equals('')) {
errorMsg = '未选择上传文件!';
}
out.print('<p class='errorMsg'>' + errorMsg + '</p>');
}
} else {
out.print('<p class='errorMsg'>创建文件夹失败!</p>');
}
%>
</div>
</body>
</html>
代码解析:
- 在
fileUpload.jsp文件中,使用ServletFileUpload类解析上传的请求,并使用DiskFileItemFactory类创建临时文件存储上传的文件。 - 使用
setSizeMax方法限制上传文件的大小,本例中限制为 2MB。 - 通过遍历
FileItem对象,判断是否为文件类型,并进行文件保存操作。 - 在文件保存之前,判断文件大小是否超过限制,如果超过则不保存并提示错误信息。
- 获取上传文件的扩展名,根据扩展名进行文件类型判断,并对不同类型的文件进行不同的处理。
- 如果上传的是 jsp 文件,则提示不允许上传。
- 如果上传的是图片文件,则在页面上显示该图片,并设置图片样式。
运行结果:
- 成功上传小于 2MB 的文件:
- 显示成功提示信息。
- 对于图片文件,显示图片预览。
- 上传超过 2MB 的文件:
- 显示错误提示信息:
上传文件大小超过限制(2MB)!
- 显示错误提示信息:
- 上传 jsp 文件:
- 显示错误提示信息:
不允许上传jsp文件!
- 显示错误提示信息:
总结:
本案例演示了如何使用 Java 和 Apache Commons FileUpload 库实现文件上传功能,并限制上传文件的大小。同时,还演示了如何根据文件名扩展名进行文件类型判断,并对不同类型文件进行不同的处理。你可以根据实际需求对代码进行修改和扩展。
原文地址: https://www.cveoy.top/t/topic/mt5c 著作权归作者所有。请勿转载和采集!