1.在web工程中引入两个jar文件:commons-fileupload-1.1.1.jar和commons-io-1.3.1.jar
2.创建一个servlet文件upload.java
upload.java code:
package myweb;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import myweb.DBConnection;
import java.sql.*;
import java.net.InetAddress;
import java.util.Calendar;
/**
*
* @author zhupan
*
*/
public class upload extends HttpServlet {
public upload() {
try {
jbInit();
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
*
*/
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html; charset=GB2312");
PrintWriter out = response.getWriter();
String type = request.getParameter("type"); //上传文件的类型
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload sevletFileUpload = new ServletFileUpload(factory);
// 设置允许用户上传文件大小,单位:字节,这里设为2m
//sevletFileUpload.setSizeMax(2 * 1024 * 1024);
// 设置最多只允许在内存中存储的数据,单位:字节
factory.setSizeThreshold(4096);
// 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
factory.setRepository(new File("d://temp"));
// 开始读取上传信息
List fileItems = sevletFileUpload.parseRequest(request);
// 依次处理每个上传的文件
Iterator iter = fileItems.iterator();
// 正则匹配,过滤路径取文件名
String regExp = ".+(.+)$";
// 过滤掉的文件类型
String[] errorType;
if (type.equals("1")) { //文本文件
errorType = new String[] {".exe", ".com", ".cgi", ".ini",
".sys",
".bat", ".asp", ".jsp", ".jpg", ".gif",
".bmp",
".dll", ".html", ".htm", ".java", ".class", ".zip",
".rar", ".avi", ".mp3", ".wmv", ".txt"};
sevletFileUpload.setSizeMax(2 * 1024 * 1024);
} else if (type.equals("2")) { //应用软件
errorType = new String[] {".com", ".cgi", ".ini",
".sys",
".bat", ".asp", ".jsp", ".jpg", ".gif",
".bmp",
".dll", ".html", ".htm", ".java", ".class", ".avi",
".mp3", ".wmv", ".doc", ".xls", ".txt", ".rtf",
".txt"};
sevletFileUpload.setSizeMax(20 * 1024 * 1024);
} else if (type.equals("3")) { //音乐文件
errorType = new String[] {".com", ".cgi", ".ini",
".sys",
".bat", ".asp", ".jsp", ".jpg", ".gif",
".bmp",
".dll", ".html", ".htm", ".java", ".class", ".doc",
".xls", ".txt", ".rtf", ".rar", ".zip", ".txt"};
sevletFileUpload.setSizeMax(10 * 1024 * 1024);
} else { //
errorType = new String[] {".exe", ".com", ".cgi", ".ini",
".sys",
".bat", ".asp", ".jsp", ".dll", ".html", ".htm",
".java", ".class", ".txt"};
sevletFileUpload.setSizeMax(5 * 1024 * 1024);
}
Pattern p = Pattern.compile(regExp);
out.print("<html>");
out.print("<head><title>上传提示页</title>");
out.print(
"<link rel=stylesheet href=../css/treecss.css type=text/css></head>");
out.print("<body bgcolor=#f7ffff>");
out.print("<div align=center><table width=98% cellpadding=5 cellspacing=1><tr><td align=left class=td1> <font color=#2E75BB><b>上传文件提示</b></font></td></tr></table></div>");
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
// 忽略其他不是文件域的所有表单信息
if (!item.isFormField()) {
String name = item.getName();
long size = item.getSize();
if ((name == null || name.equals("")) && size == 0)
continue;
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.print("");
out.print("");
throw new IOException(name + ": 非法文件类型禁止上传");
}
}
try {
// 保存上传的文件到指定的目录
// 在下文中上传文件至数据库时,将对这里改写开始
out.print(
"<div align=center><table width=98% cellpadding=5 cellspacing=1>");
out.print(
"<tr><td align=left ><img src='../img/tp001.gif'> <b>上传成功</b></td></tr>");
out.print("<tr><td>文件名:" + name + "</td></tr>");
out.print("<tr><td>文件大小:" + size / 1024 +
"KB</td></tr>");
out.print("<br>");
out.print("</table></div>");
Calendar c = Calendar.getInstance();
String n = c.toString().substring(33, 46);
String r = item.getName();
r = r.substring(r.lastIndexOf("."));
String a = n.concat(r);
if (type.equals("1")) { //表单
item.write(new File("d://myweb//E-gov//uploadfile//table//" +a));
} else if (type.equals("2")) {//应用软件
item.write(new File("d://myweb//E-gov//uploadfile//soft//" +a));
} else if (type.equals("3")) { //音乐
item.write(new File("d://myweb//E-gov//uploadfile//music//" +a));
} else {
item.write(new File("d://myweb//E-gov//uploadfile//temp//" +a));
}
String t_name = name.substring(name.lastIndexOf("//") + 1);
Connection con = null;
con = DBConnection.getConnection();
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
if (type.equals("1")) { //表单
stmt.execute("insert into resource (table_name,ADDRESS,SIZE,DOWNLOAD_TIMES,type) values('" +t_name + "','" + a + "','" +size / 1024 + "',0,1)");
} else if (type.equals("2")) {
stmt.execute("insert into resource (table_name,ADDRESS,SIZE,DOWNLOAD_TIMES,type) values('" +t_name + "','" + a + "','" +size / 1024 + "',0,2)");
} else if (type.equals("3")) { //音乐
stmt.execute("insert into resource (table_name,ADDRESS,SIZE,DOWNLOAD_TIMES,type) values('" +t_name + "','" + a + "','" +size / 1024 + "',0,3)");
} else {
stmt.execute("insert into resource (table_name,ADDRESS,SIZE,DOWNLOAD_TIMES,type) values('" +t_name + "','" + a + "','" +size / 1024 + "',0,0)");
}
stmt.close();
con.close();
// 在下文中上传文件至目录时,将对这里改写结束
} catch (Exception e) {
out.println(e);
}
} else {
throw new IOException("fail to upload");
}
}
}
out.print("</body></html>");
} catch (IOException e) {
out.println(e);
} catch (FileUploadException e) {
out.println(e);
}
}
private void jbInit() throws Exception {
}
}
3.html页面
<html>
<head>
<title>upload</title>
<link rel="stylesheet" href="../css/common.css" type="text/css"/>
<script language=JavaScript type="">
function fAddAttach(m){
var gAttchHTML='<div class="tdtext"></div><div class="le"><input type="file" name="attachfile[]" class="box" size=40><input type="button" name="Submit" value="/u522a/u9664" class="box" id="btnDeleteReadAttach" /></div><span></span>';
var Attach=document.getElementById("dvReadAttach"+m);
var spnList=Attach.getElementsByTagName("SPAN");
var spn=document.createElement("DIV");
spn.className="qrc4";
spn.innerHTML=gAttchHTML;
spn.childNodes[1].childNodes[0].name="attachfile[]" + spnList.length;
Attach.appendChild(spn);
fGetObjInputById(spn,"btnDeleteReadAttach").οnclick=function(){fDeleteAttach(this,m);};
document.getElementById("aAddAttach"+m).innerHTML="继续添加";
Attach.style.display="";
}
function fGetObjInputById(obj,id){
var inputList=obj.getElementsByTagName("INPUT");
for(var i=0;i<inputList.length;i++){
if(inputList[i].id==id){
return inputList[i];
}
}
return null;
}
function fDeleteAttach(obj,m){
try{
obj.parentNode.parentNode.parentNode.removeChild(obj.parentNode.parentNode);
var Attach=document.getElementById("dvReadAttach"+m);
var spnList=Attach.getElementsByTagName("SPAN");
if(spnList.length==0){
document.getElementById("aAddAttach"+m).innerHTML="继续添加";
Attach.style.display="none";
}else{
document.getElementById("aAddAttach"+m).innerHTML="继续添加";
}
}catch(exp){
}
}
</script>
</head>
<body>
<div align="center">
<table width="98%" cellpadding="5" cellspacing="1">
<tr><td align=left class="td1"> <font color=#2E75BB><b>常用表格单据上传</b></font></td></tr>
<tr><td>提示信息:</td></tr>
<tr><td>1.单击“浏览”选择需要上传服务器端的表格单据文件,路径选择完成后单击“上传”完成文件上载。</td></tr>
<tr><td>2.常用表格单据上传功能仅支持后缀为doc/docx/xls/pdf的文件。</td></tr>
<tr><td>3.由于存储空间限制,该功能暂限制单个上传文件最大为2m。</td></tr>
<form action="upload?type=1" name="uploadform" method="POST" enctype="multipart/form-data">
<tr><td><div id="dvReadAttach1" style="display:none"></div><a href="javascript:fAddAttach(1);" id="aAddAttach1">添加文件</a><br>
<input type="submit" name="upload" value="上 传" class="submit" οnclick="javascript:return confirm('您确认要上传此文件?')"></td></tr>
</form>
</table>
</div>
</body>
</html>
4.配置web.xml
目录结构:../E-gov/resource/upload.html
../myweb/upload.java
<servlet>
<servlet-name>upload</servlet-name>
<servlet-class>myweb.upload</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>upload</servlet-name>
<url-pattern>/resource/upload</url-pattern>
</servlet-mapping>