用了commons-fileupload-1.2.jar和commons-io-1.3.2.jar这两个包。
save.jsp
<%@ page language="java" contentType="text/html;charset=utf-8"%>
<%@ page import="java.util.*"%>
<%@ page import="java.io.*"%>
<%@ page import="java.util.regex.*"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="java.sql.*"%>
<html>
<head>
<title>保存上传文件</title>
</head>
<body bgcolor='#FFFFFF' text='#000000' leftmargin='0' topmargin='40' marginwidth='0' marginheight='0'>
<font size='6' color='blue'>文件列表:</font>
<center>
<table cellpadding=0 cellspacing=1 border=1 width='100%'>
<tr>
<td bgcolor=#008080>文件名</td>
<td bgcolor=#008080>大小</td>
</tr>
<%
// 连接字
String SQL_CON_DRIVER = "com.mysql.jdbc.Driver";
String SQL_CON_USERNAME = "root";
String SQL_CON_PASSWORD = "ddd";
String SQL_CON_STRING = "jdbc:mysql://localhost/ddd?useUniCode=true&characterEncoding=utf-8";
// 连接驱动
try{
Class.forName(SQL_CON_DRIVER).newInstance();
}
catch(ClassNotFoundException e){
out.print(e);
}
// 连接
Connection conn = DriverManager.getConnection(SQL_CON_STRING,SQL_CON_USERNAME,SQL_CON_PASSWORD);
ResultSet rs = null;
PreparedStatement pstmt=conn.prepareStatement("insert into require_file(file_name,file_content) values(?,?)");
%><%
int errorType_int =1;
String msg = "";
DiskFileUpload fu = new DiskFileUpload();
// 设置允许用户上传文件大小,单位:字节
//fu.setSizeMax(2*1024*1024);//2m
// 设置最多只允许在内存中存储的数据,单位:字节
fu.setSizeThreshold(4096);
// 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
//(临时存放目录,文件上传完毕后有办法清除它吗?)
// fu.setRepositoryPath("D://TEMP");
//开始读取上传信息
List fileItems = fu.parseRequest(request);
// 依次处理每个上传的文件
Iterator iter = fileItems.iterator();
//正则匹配,过滤路径取文件名
String regExp=".+////(.+)$";
//过滤掉的文件类型
String[] errorType={"exe","com","cgi","asp","jsp"};
Pattern p = Pattern.compile(regExp);
while (iter.hasNext())
{
FileItem item = (FileItem) iter.next();
//忽略其他不是文件域的所有表单信息
if (!item.isFormField())
{
String name = item.getName();//获取上传的文件名
long size = item.getSize();//获取上传的文件大小(字节为单位)
if(size>=2*1024*1024){
out.println("文件大小超过2M");
break;
}
if((name==null||name.equals("")) && size==0||size>=2*1024*1024)
{
continue;//跳到while检查条件
}
Matcher m = p.matcher(name);
boolean result = m.find();
//以下为文件名处理。
if (result){
for (int temp=0;temp<errorType.length;temp++){
if (m.group(1).endsWith(errorType[temp])){
out.println(name+": wrong type");
errorType_int=0;
//throw new IOException(name+": wrong type");
}
}
// if(errorType_int!=0)
try{
//PreparedStatement pstmt=conn.prepareStatement("insert into require_file(file_name,file_size,file_version,file_uploader,file_alter,file_content) values(?,?)");
////////////////////////////////////////////////////////////////////////////////////////////////////////
if(errorType_int!=0){
int byteread=0;
InputStream inStream=item.getInputStream(); //读取输入流,也就是上传的文件内容
pstmt.setString(1,m.group(1));
pstmt.setBinaryStream(2,inStream,(int)size);
pstmt.executeUpdate();
inStream.close();
out.println(name+" "+size+"<br>");
errorType_int=1;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
//上传到目录
if(errorType_int!=0){
//item.write(new File("d://" + m.group(1)));
//out.print(name+" "+size+"<br>");
//获取文件名字符串的长度
int end = name.length();
//返回在此字符串中最右边出现的指定子字符串的索引。
int begin = name.lastIndexOf("//");
File savedFile = new File(fu.getRepositoryPath(), name.substring(begin+1,end));
item.write(savedFile);
out.println("<tr>");
out.println("<td>" + name + "</td>");
out.println("<td>" + size + "</td>");
errorType_int=1;
}
*/
}
catch(Exception e){
// 回滚事务,如不需要可去掉
try{conn.rollback ();} catch (java.sql.SQLException ignore){}
out.println(e);
}finally{}
}
else{
throw new IOException("fail to upload");
}
}
}
if (pstmt != null) {
try { pstmt.close(); } catch (java.sql.SQLException ignore) {}
}
if (conn != null) {
try { conn.close(); } catch (java.sql.SQLException ignore) {}
}
%></table>
<br><br>
<a href="index.html">返回上传页面</a>
</center>
</body>
</html>
down.jsp
<%@ page language="java" import="java.net.*" pageEncoding="utf-8"%><%@ page import="java.sql.*"%><%@ page import="java.util.*"%><%@ page import="java.text.*"%><%@ page import="java.io.*"%><%
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://localhost/ddd?user=root&password=&useUnicode=true&characterEncoding=utf-8";
//其中mysql为你数据库的名字,user为你连接数据库的用户,password为你连接数据库用户的密码,可自己改
Connection conn = DriverManager.getConnection(url, "root", "ddd");
ResultSet rs = null;
int down_id=0;
String down_id_string = request.getParameter("down_id");
if(down_id_string==null){
out.println("没有你要下载的文件");
}
else{
down_id=Integer.parseInt(down_id_string); //获得下载的文件id
}
String sql = "select file_name,file_content from require_file where id="+down_id+"";
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
} catch (SQLException e) {
}
try {
if (rs.next()) {
response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(rs.getString("file_name"),"UTF-8"));
response.setHeader("Connection", "close");
response.setHeader("Content-Type", "application/octet-stream");
ServletOutputStream sout = response.getOutputStream();
InputStream in = rs.getBinaryStream("file_content");
byte b[] = new byte[1024*8];
for(int i=in.read(b);i!=-1;)
{
sout.write(b);
i=in.read(b);
}
sout.flush();
sout.close();
in.close();
}
} catch (Exception e) {
System.out.println(e);
}finally
{
if(rs != null)
{
rs.close();
}
if(stmt != null)
{
stmt.close();
}
if(conn != null)
{
conn.close();
}
}
%>
来源:https://www.cnblogs.com/fan-xiaofan/p/5818520.html