有几个需要注意的地方:
1、<input name="uploadStatement" type="file">必须定义在<form></form>标签内
2、<form>标签必须定义name,method="post",enctype="multipart/form-data"三个属性
测试页面(myTest.jsp):
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>myTest</title>
</head>
<body>
<form name="form1" action="importStatementEng.jsp" method="post" enctype="multipart/form-data">
<h3 align="center">文件上传</h3>
<p align="center">请选择上传文件:
<input name="uploadStatement" type="file">
</p>
<p align="center">
<label>
<input type="submit" name="Submit" value="提交">
</label>
<label>
<input type="reset" name="Submit2" value="重置">
</label>
</p>
</form>
</body>
</html>
处理上传附件的jsp文件(importStatementEng.jsp):
<%@ page contentType="text/html;charset=GB2312"%>
<%@ page import="javax.servlet.ServletInputStream"%>
<%@ page import="javax.servlet.http.HttpServletRequest"%>
<%@ page import="javax.servlet.http.HttpServletResponse"%>
<%@ page import="java.io.*"%>
<%@ page import="java.util.*"%>
<html>
<head>
<title>untitled</title>
</head>
<body>
<script>
alert('开始对导入文件进行处理');
</script>
<%
String filename = null;
ServletInputStream in = request.getInputStream();
try
{
byte[] line = new byte[128];
int i = in.readLine(line, 0, 128);
if (i < 3)
throw new Exception("读取请求流第一行出错");
int boundaryLength = i - 2;
String boundary = new String(line, 0, boundaryLength); //-2丢弃换行字符
while (i != -1) //判断是否为文件尾部
{
String newLine = new String(line, 0, i);
if (newLine.indexOf("Content-Disposition: form-data; name=/"")!=-1)
{
if (newLine.indexOf("filename=/"") != -1)
{
//文件内容
i = in.readLine(line, 0, 128);//读取"filename="上载文件绝对路径""
i = in.readLine(line, 0, 128);//读取"Content-Type:text/html"
i = in.readLine(line, 0, 128);//读取空行
newLine = new String(line, 0, i);
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(new File("D:/MyUplodFile.txt"))));
while (i != -1 && !newLine.startsWith(boundary)) //开始读取上载文件正文,并写入磁盘
{
// 文件内容的最后一行包含换行字符
// 因此我们必须检查当前行是否是最
// 后一行
i = in.readLine(line, 0, 128);
if ((i==boundaryLength+2 || i==boundaryLength+4)&& (new String(line, 0, i).startsWith(boundary)))//判断是否为请求流尾部分隔符
pw.print(newLine.substring(0, newLine.length()-2));
else
pw.print(newLine);
newLine = new String(line, 0, i);
}//end while
pw.close();
}//end if
}//end if
i = in.readLine(line, 0, 128);
}//end while
in.close();
}catch (Exception e)
{
in.close();
}
%>
</body>
</html>