准备工作:
导入jar包
- 文件上传依赖包: commons-fileupload-1.3.3.jar 和 commons-io-2.6.jar
- jsp标准标签库: jstl.jar 和 standard.jar
导入jquery-3.4.1.js
文件上传
FileUpload.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件上传</title>
</head>
<script type="text/javascript" src="js/jquery-3.4.1.js"></script>
<script type="text/javascript">
window.onload = function () {
$("#uloadFile").on('change', function () {
var filesize = this.files[0].size;
alert("文件大小"+filesize);
});
}
</script>
<body>
<form action="http://192.168.1.18:8080/fileupload" method="post" enctype="multipart/form-data">
选择一个文件:
<input type="file" name="uploadFile" id="uloadFile"/>
<br/><br/>
<input type="submit" value="上传"/>
</form>
</body>
</html>
上传后的消息显示
message.jsp (此处加入了服务器保存的文件查看的超链接)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件上传结果</title>
</head>
<body>
<h2>${message}</h2>
<a href="http://192.168.1.18:8080/selectFile">文件查看</a>
</body>
</html>
文件上传功能转自https://www.runoob.com/jsp/jsp-file-uploading.html
文件查看和下载部分
js中实现了文件的下载(post请求 以表单形式提交文件信息 : 文件名和文件绝对路径 )
FileSelect.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>下载</title>
<meta content="text/html; charset=utf-8"/>
</head>
<script type="text/javascript" src="js/jquery-3.4.1.js"></script>
<script type="text/javascript">
function file(name, path,action) {
var form = $("<form action='http://192.168.1.18:8080/fileHandle' method='post'></form>");
var filename = $("<input type='hidden'name='name'>");
var filepath = $("<input type='hidden'name='path'>");
var fileaction = $("<input type='hidden'name='action'>");
filename.attr("value",name);
filepath.attr("value",path);
fileaction.attr("value",action);
form.append(filename);
form.append(filepath);
form.append(fileaction);
$("html").append(form);
form.submit();
}
</script>
<body>
<table border="1" align="center" cellpadding="0" cellspacing="0">
<c:forEach items="${list}" var="fileInfo">
<tr height="40px">
<td width="100px" align="center">文件名</td>
<td width="200px" align="center">${fileInfo.filename}</td>
<td width="150px" align="center">文件路径</td>
<td width="200px" align="center">${fileInfo.filepath}</td>
<td width="50px" align="center"><a href="javascript:void(0);" onclick="file('${fileInfo.filename}','${fileInfo.transpath}','download')">下载</a>
</td>
<td width="50px" align="center"><a href="javascript:void(0);" onclick="file('${fileInfo.filename}','${fileInfo.transpath}','delete')">删除</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
文件下载是否成功的提示
success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${message}
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${message}
</body>
</html>
web.xml中的配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>UpLoad</servlet-name>
<servlet-class>com.lly.Fileupload</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UpLoad</servlet-name>
<url-pattern>/fileupload</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>selectFile</servlet-name>
<servlet-class>com.lly.FileSelect</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>selectFile</servlet-name>
<url-pattern>/selectFile</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>fileHandle</servlet-name>
<servlet-class>com.lly.fileHandle</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fileHandle</servlet-name>
<url-pattern>/fileHandle</url-pattern>
</servlet-mapping>
</web-app>
后台servlet编写
文件上传 Fileupload.class
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
@WebServlet(name = "Fileupload")
public class Fileupload extends HttpServlet {
private static final long serialVersionUID = 1L; //序列号
// 上传文件存储目录
public static final String UPLOAD_DIRECTORY = "LLYSpace";
// 上传配置
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 30; // 30MB //内存阈值
private static final int MAX_FILE_SIZE = 1024 * 1024 * 400; // 400MB //最大文件大小
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 500; // 500MB //最大请求大小
/**
* 上传数据及保存文件
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
FileUpload(request, response);
}
private synchronized void FileUpload(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html; charset=utf-8");
//设置字符集编码用于支持汉字显示
request.setCharacterEncoding("utf-8");
// 检测是否为多媒体上传
if (!ServletFileUpload.isMultipartContent(request)) {
// 如果不是则停止
PrintWriter writer = response.getWriter();
writer.println("Error: 表单必须包含 enctype=multipart/form-data");
writer.flush();
return;
}
// 配置上传参数 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
factory.setSizeThreshold(MEMORY_THRESHOLD);
// 设置临时存储目录()
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
// 用以上工厂实例化上传组件
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置最大文件上传值
upload.setFileSizeMax(MAX_FILE_SIZE);
// 设置最大请求值 (包含文件和表单数据)
upload.setSizeMax(MAX_REQUEST_SIZE);
// 中文处理
upload.setHeaderEncoding("UTF-8");
// 构造临时路径来存储上传的文件
// 这个路径相对当前应用的目录
String uploadPath = getServletContext().getRealPath("/") + File.separator + UPLOAD_DIRECTORY;
System.out.println(uploadPath); //打印文件夹路径
// 如果目录不存在则创建
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
try {
// 解析请求的内容提取文件数据
@SuppressWarnings("unchecked")
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && ((List) formItems).size() > 0) {
// 迭代表单数据
for (FileItem item : formItems) {
// 处理不在表单中的字段
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
// 保存文件到硬盘
item.write(storeFile);
request.setAttribute("message", "文件上传成功!");
}
}
}
} catch (Exception ex) {
request.setAttribute("message", "错误信息: " + ex.getMessage());
}
// 跳转到 message.jsp
getServletContext().getRequestDispatcher("/message.jsp").forward(request, response);
}
}
文件查看 FileSelect.class 此处用到了文件信息对象,所有要创建一个FileInfo类存储文件信息
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class FileSelect extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String uploadPath = getServletContext().getRealPath("/") + File.separator + Fileupload.UPLOAD_DIRECTORY; //文件夹路径
File file = new File(uploadPath);
ArrayList<File> Arraylist =getAllFiles(file);
List<FileInfo> list = new ArrayList<>();
for (File file1 : Arraylist) {
FileInfo fileInformation = new FileInfo();
fileInformation.setFilename(file1.getName());
fileInformation.setFilepath(file1.getAbsolutePath());
fileInformation.setTranspath(file1.getAbsolutePath().replace(File.separator,"%2F"));
list.add(fileInformation);
}
req.setAttribute("list", list);
req.getRequestDispatcher("FileSelect.jsp").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
//遍历文件夹下所有文件放入ArrayList集合中
public ArrayList<File> getAllFiles(File file) {
ArrayList<File> list = new ArrayList<>();
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
list.addAll(getAllFiles(files[i]));
} else if (files[i].isFile()) {
list.add(files[i]);
}
}
return list;
}
文件信息类:FileInfo.class
public class FileInfo {
private String filename;
private String filepath;
private String transpath;
public FileInfo() {
}
public FileInfo(String filename, String filepath, String transpath) {
this.filename = filename;
this.filepath = filepath;
this.transpath = transpath;
}
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 getTranspath() {
return transpath;
}
public void setTranspath(String transpath) {
this.transpath = transpath;
}
@Override
public String toString() {
return "FileInfo{" +
"filename='" + filename + '\'' +
", filepath='" + filepath + '\'' +
", transpath='" + transpath + '\'' +
'}';
}
}
文件处理类:fileHandle.class 该类实现了文件的下载和文件的删除功能
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
public class fileHandle extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String action = req.getParameter("action");
if ("download".equals(action)) {
fileDownLoad(req, resp);
}
if ("delete".equals(action)) {
boolean b = fileDelete(req);
if (b) {
req.setAttribute("message", "文件删除成功");
}else {
req.setAttribute("message","文件删除失败");
}
req.getRequestDispatcher("success.jsp").forward(req, resp);
}
}
private synchronized boolean fileDelete(HttpServletRequest req) throws UnsupportedEncodingException {
String filepath = req.getParameter("path");
filepath = filepath.replace("%2F", File.separator);
File file = new File(filepath);
return file.delete();
}
/**
* System.out.println(System.getProperty("file.encoding")); //打印系统默认字符编码
* resp.addHeader("Content-Disposition", "attachment;filename=" + filename); //设置下载方式和文件名
* 注意此方法中文件名的编码格式是 ISO8859-1 所以需要使用 new String(filename.getBytes("UTF-8"),"ISO8859-1");将文件名进行转码
* 因为servlet设置了过滤器,所以请求的编码格式为 UTF-8 ,而系统的默认的字符编码为GBK,
* 所以要在控制台输出信息就需要使用 new String(str.getBytes("UTF-8"),"GBK");
*
* resp.setContentType("application/octet-stream"); //响应设置为二进制流
* resp.setContentType("application/multipart/form-data"); //设置文件ContentType类型,这样设置,会自动判断下载文件类型
*
*/
private synchronized void fileDownLoad(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String filename = req.getParameter("name");
String filepath = req.getParameter("path");
filepath = filepath.replace("%2F", File.separator); //将路径中的路径符号重新转码为系统默认符号
resp.setCharacterEncoding("utf-8"); //设置响应编码
resp.setContentType("application/multipart/form-data"); //设置文件ContentType类型,这样设置,会自动判断下载文件类型
resp.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("UTF-8"),"ISO8859-1")); //设置下载方式和文件名
File file = new File(filepath);
InputStream in = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(in); //读取服务器中的文件
BufferedOutputStream ous = new BufferedOutputStream(resp.getOutputStream()); //向客户端响应流文件
byte[] bytes = new byte[1024];
while (bis.read(bytes) != -1) {
ous.write(bytes);
ous.flush();
}
ous.close();
bis.close();
}
}
在类中使用了servlet的响应流resp.getOutputStream()