直接上运行效果
注意事项(代码较多,放在后面)
- 导入 .jar包 ,使用Maven时,不需要手动导入 jar包 ,在pom.xml文件中加入依赖即可,加入之后点击右侧Maven图标,并按刷新按钮,Maven会自动更新和下载jar包(如图)
- 有些需要本地导入的jar包,操作方法如下:
- 将jar包导入Maven本地仓库,然后可以在项目中使用
在cmd窗口中输入下面的代码,即可将jar包导入本地仓库
mvn install:install-file
-Dfile=G:\File\JavaTool_File\jar\common-fileUpLoad\commons-fileupload-1.4.jar
-DgroupId=RedMaple
-DartifactId=FileUpLoad.sources
-Dversion=1.0
-Dpackaging=jar
Dfile 为绝对路径
DgroupId,DartifactId,Dversion 分别对应pom.xml文件中的groupId,artifactId,version
Dpacking=jar 照抄,注意D前面都有 - 号
成功后,就在pom.xml的 dependency中加入如下内容即可
<dependency>
<groupId>RedMaple</groupId>
<artifactId>Commons.lang3</artifactId>
<version>1.0</version>
</dependency>
关于Java接收上传文件具体内容
- 需要引入的依赖
<!--Common-FileUpLoad包-->
<dependency>
<groupId>RedMaple</groupId>
<artifactId>FileUpLoad.sources</artifactId>
<version>1.0</version>
</dependency>
<!--Common-Io包-->
<dependency>
<groupId>RedMaple</groupId>
<artifactId>Commons.Io</artifactId>
<version>1.0</version>
</dependency>
// Servlet 文件上传
public class UploadServlet extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
res.setContentType("text/plain;charset=UTF-8");
PrintWriter pw = res.getWriter();
try{
DiskFileItemFactory diskFactory = new DiskFileItemFactory();
// threshold 极限、临界值,即硬盘缓存 1M
diskFactory.setSizeThreshold(4 * 1024);
// repository 贮藏室,即临时文件目录
diskFactory.setRepository(new File("G:\\File\\Temp_File"));
ServletFileUpload upload = new ServletFileUpload(diskFactory);
// 设置允许上传的最大文件大小 4M
upload.setSizeMax(4 * 1024 * 1024);
// 解析HTTP请求消息头(得到请求参数的集合)
List<FileItem> fileItems = upload.parseRequest(req);
// 进行迭代
Iterator<FileItem> iter = fileItems.iterator();
while(iter.hasNext())
{
FileItem item = (FileItem)iter.next();
// 判断是否是普通表单
if(item.isFormField())
{
// 是普通表单
System.out.println("处理表单内容 ...");
processFormField(item, pw);
}else{
// 不是普通表单
System.out.println("处理上传的文件 ...");
processUploadFile(item, pw);
}
}
}catch(Exception e){
System.out.println("使用 fileupload 包时发生异常 ...");
e.printStackTrace();
}finally{
pw.close();
}
}
// 处理表单内容
private void processFormField(FileItem item, PrintWriter pw) throws Exception {
String name = item.getFieldName(); // 获取参数名称
String value = item.getString(); // 获取值
}
// 处理上传的文件
private void processUploadFile(FileItem item, PrintWriter pw) throws Exception {
// 不同浏览器得到的getName()是不一样的,是否要加工再具体讨论
// 有的是绝对路径有的是文件名
String filename = item.getName();
// 获取文件大小
long fileSize = item.getSize();
// 创建一个接收该文件的文件模板
File uploadFile = new File("G:\\File\\Txt_File" + "/" + filename);
//将文件读取并写入模板中
item.write(uploadFile);
}
}
用到的Gson类
- 要用到的依赖
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.3</version>
</dependency>
// 将 filesArrayList对象 变为 Json字符串
Gson gson = new Gson();
json = gson.toJson(filesArrayList);
最后,使用了Maven的pom.xml 文件之后,似乎不需要WEB-INF文件夹下的lib文件夹来存放jar包了。(刚用Maven不久,只是猜测,有人会的话可以评论教教我)
核心代码
接收并将文件信息存入数据库
// Servlet 文件上传
public class UploadServlet extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
res.setContentType("text/html;charset=utf-8");
PrintWriter pw = res.getWriter();
try{
DiskFileItemFactory diskFactory = new DiskFileItemFactory();
// threshold 极限、临界值,即硬盘缓存 1M
diskFactory.setSizeThreshold(4 * 1024);
// repository 贮藏室,即临时文件目录
diskFactory.setRepository(new File("G:\\File\\Temp_File"));
ServletFileUpload upload = new ServletFileUpload(diskFactory);
// 设置允许上传的最大文件大小 1G
upload.setSizeMax(1024 * 1024 * 1024);
// 解析HTTP请求消息头
List<FileItem> fileItems = upload.parseRequest(req);
Iterator<FileItem> iter = fileItems.iterator();
while(iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if(!item.isFormField()){
System.out.println("处理上传的文件 ...");
processUploadFile(item,pw,req,res);
}
}
}catch(Exception e){
System.out.println("使用 fileupload 包时发生异常 ...");
e.printStackTrace();
}finally {
pw.close();
}
}// end doPost()
// 处理上传的文件
private void processUploadFile(FileItem item, PrintWriter pw,HttpServletRequest req
,HttpServletResponse res) throws Exception {
// 此时的文件名包含了完整的路径,得注意加工一下
String fileName = item.getName();
int index = fileName.lastIndexOf(".");
String extension = fileName.substring(index+1,fileName.length());
long fileSize = item.getSize();
String filePath = "G:\\File\\Temp_File" + "/" + fileName;
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String time = sdf.format(date);
File uploadFile = new File(filePath);
item.write(uploadFile);
Files files = new Files(fileName,String.valueOf(fileSize),filePath,time);
addFile(files);
req.getRequestDispatcher("T03.jsp").forward(req,res);
}
private void addFile(Files files){
Connection conn = Mysql.connection("filesys");
String sql = "insert into file(filename,filesize,filepath,time) values(?,?,?,?);";
PreparedStatement ps = Mysql.prepareStatement(conn,sql);
Mysql.setString(ps,1,files.fileName);
Mysql.setString(ps,2,files.fileSize);
Mysql.setString(ps,3,files.filePath);
Mysql.setString(ps,4,files.time);
Mysql.executeUpdate(ps);
Mysql.close(conn,ps);
}
}
读取数据,并将数据以Json格式发送给前端AJAX
public class GetDate extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
String[] filesArrayList = new String[100];
boolean flag = findFile(filesArrayList);
String json = "{:}";
if(flag){
Gson gson = new Gson();
json = gson.toJson(filesArrayList);
}
response.setContentType("text/html;charset=utf-8");
PrintWriter pw = response.getWriter();
pw.println(json);
}
private boolean findFile(String[] filesArrayList){
boolean flag = false;
Connection conn = Mysql.connection("filesys");
String sql = "select * from file;";
PreparedStatement ps = Mysql.prepareStatement(conn,sql);
ResultSet rs = Mysql.executeQuery(ps);
int i = 0;
while(Mysql.next(rs)){
String fileName = Mysql.getString(rs,"filename");
String fileSize = Mysql.getString(rs,"filesize");
String filePath = Mysql.getString(rs,"filepath");
String time = Mysql.getString(rs,"time");
Files files = new Files(fileName,fileSize,filePath,time);
Gson gson = new Gson();
filesArrayList[i++] = gson.toJson(files);
flag = true;
}
Mysql.close(conn,ps);
return flag;
}
}
AJAX和JQuery联用,将文件信息在前端展示
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false"%>
<html>
<head>
<script type='text/javascript' src='jQuery-3.6.js'></script>
<script>
$(function(){
var data = '';
var num = 1;
$.get("get",data,function(resp){
$.each(resp,function(i,file){
if(file!=null){
var json = JSON.parse(file);
var index = json.fileName.lastIndexOf(".");
var extension = json.fileName.substring(index,json.fileName.length);
$("table").append(
"<tr>" +
"<td>" + (num++) +"</td>" +
"<td>" + json.fileName+"</td>" +
"<td>" + extension +"</td>" +
"<td>" + json.fileSize+"</td>" +
"<td>" + json.filePath+"</td>" +
"<td>" + json.time+"</td>" +
"<td>" + json.fileName+"</td>" +
"</tr>"
);
}
})
},"json");
})
</script>
<style>
table{
margin-top:10px;
border:1px black solid;
}
.tableTitle{
width:150px;
background-color: rgb(130, 113, 204);
color:white;
font-size:17px;
}
td{
text-align:center;
outline: 1px white solid;
background-color: rgb(222,223,222);
}
</style>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
上传文件列表:
<input type='file' id='file' name="file">
<input type='submit' value='上传'>
</form>
<table>
<tr>
<td class='tableTitle'>自动序列</td>
<td class='tableTitle'>文件名</td>
<td class='tableTitle'>扩展名</td>
<td class='tableTitle'>文件大小</td>
<td class='tableTitle'>文件路径</td>
<td class='tableTitle'>上传时间</td>
<td class='tableTitle'>备注说明</td>
</tr>
</table>
</body>
</html>
相关配置信息
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--加入Servlet依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>RedMaple</groupId>
<artifactId>FileUpLoad</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>RedMaple</groupId>
<artifactId>FileUpLoad.sources</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>RedMaple</groupId>
<artifactId>Commons.Io</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>RedMaple</groupId>
<artifactId>Mysql</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.3</version>
</dependency>
<dependency>
<groupId>RedMaple</groupId>
<artifactId>Commons.lang3</artifactId>
<version>1.0</version>
</dependency>
</dependencies>