在网上看了一些,可能是因为我太菜了,没找到想要的,然后就整理了一下自己写了一个。
用到的东西:
前端:纯html,一个表单
后端:servlet
数据库:mysql
插件:Fileupload
所有jar包和代码免费下载
首先是前端页面,提供一个form表单,选择上传文件
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>File Upload:</h3>
<!-- form表单提交-->
<form action="/UploadServlet" method="post" enctype="multipart/form-data">
<input type="file" name="file" size="50"/>
<br/>
<input type="submit" value="Upload File"/>
</form>
</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_3_1.xsd"
version="3.1">
<context-param>
<param-name>file-upload</param-name>
<param-value>G:\uploadFile</param-value>
</context-param>
</web-app>
编写servlet,获取上传文件的路径,进行验证,上传至指定得到文件路径。调用insertdao,将文件名及文件路径存入数据库中。这里需要注意路径的转义//要换成。
package com.yang;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletContext;
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.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
ServletContext context = request.getServletContext();
//获取web.xml中设置的上传路径
String filePath = context.getInitParameter("file-upload");
//文件路径需要进行转义,否则存入数据库的格式不对
filePath.replaceAll("//","");
//设置文件大小
int maxFileSize = 5000 * 1024;
int maxMemSize = 5000 * 1024;
File file;
//验证上传内容
String contentType = request.getContentType();
if ((contentType.indexOf("multipart/form-data") >= 0)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置内存中存储文件的最大值
factory.setSizeThreshold(maxMemSize);
// 本地存储的数据大于 maxMemSize.
factory.setRepository(new File("G:\\tempFile"));
// 创建一个新的文件上传处理程序
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置最大上传的文件大小
upload.setSizeMax(maxFileSize);
try {
// 使用插件,解析获取的文件
List fileItems = upload.parseRequest(request);
// 处理上传的文件 使用迭代器
Iterator i = fileItems.iterator();
//这是向前端页面输出显示的
response.getWriter().println("<html>");
response.getWriter().println("<head>");
response.getWriter().println("<title>JSP File upload</title>");
response.getWriter().println("</head>");
response.getWriter().println("<body>");
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if (!fi.isFormField()) {
// 获取上传文件的参数
String fieldName = fi.getFieldName();
String fileName = fi.getName();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
System.out.println(fieldName);
System.out.println(isInMemory);
System.out.println(sizeInBytes);
// 写入文件
if (fileName.lastIndexOf("\\") >= 0) {
file = new File(filePath,
fileName.substring(fileName.lastIndexOf("\\")));
} else {
file = new File(filePath,
fileName.substring(fileName.lastIndexOf("\\") + 1));
}
fi.write(file);
response.getWriter().println("Uploaded Filename: " + filePath +
fileName + "<br>");
//向数据库中存
//获取对象
InsertDao insertDao = new InsertDao();
insertDao.insert(fileName,filePath);
}
}
response.getWriter().println("<a href=\"../yang/downLoadFile.html\">点击下载</a>");
response.getWriter().println("</body>");
response.getWriter().println("</html>");
} catch (Exception ex) {
System.out.println(ex);
}
} else {
response.getWriter().println("<html>");
response.getWriter().println("<head>");
response.getWriter().println("<title>Servlet upload</title>");
response.getWriter().println("</head>");
response.getWriter().println("<body>");
response.getWriter().println("<p>No file uploaded</p>");
response.getWriter().println("</body>");
response.getWriter().println("</html>");
}
}
}
编写dao
package com.yang;
import org.junit.Test;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
public class InsertDao {
public void insert(String filename,String filepath){
//1. 获取连接对象
Connection conn=null;
Statement statement=null;
//2. 建立连接,运行sql
try {
//建立连接
conn= JDBCUtils.getConnection();
//sql
String sql="INSERT INTO file VALUES(null,'"+filename+"','"+filepath+"')";
// String sql="INSERT INTO file VALUES(null ,'201617401马云飞素质拓展审核认定表.doc',' G:\\uploadFile')";
//获取statement对象
statement = conn.createStatement();
//执行
int count = statement.executeUpdate(sql);
if (count>0){
System.out.println("执行成功。");
}else {
System.out.println("执行失败");
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCUtils.close(statement,conn,null);
}
}
}
JDBCUtils
package com.yang;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/*
durid连接池的工具类
*/
public class JDBCUtils {
//1.定义成员变量DataSource
private static DataSource ds;
//静态代码块进行初始化连接
static {
try {
//2. 加载配置文件
Properties pro = new Properties();
pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
//3. 获取连接池
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
获取连接
*/
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
/*
释放资源
*/
public static void close(Statement stmt,Connection conn){
close(stmt,conn,null);
}
//含有resultSet的关闭
public static void close(Statement stmt, Connection conn, ResultSet rs){
if (stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//获取连接池的方法
public static DataSource getDataSurce(){
return ds;
}
}