自己编写JAVA环境下的文件上传组件
上传文件是经常用到的,B/S环境下的文件上传原理其实和带附件的Email一样,HTTP数据流
由标志性的数据加上文件数据组成,你只要得到数据流将其标志性数据去掉,剩下的就是你
的数据文件了,在将其写成文件就完成了上传。
下面我们分布说明:
1.上传文件的静态页面,我们一定要确认method="post" enctype="multipart/form-data"
为什么就不要说了吧。
<%@ page contentType="text/html; charset=GBK" %>
<html>
<head>
<title> browsefile </title>
</head>
<body>
<h1> test2 </h1>
<FORM method="post" enctype="multipart/form-data" action="iFileUpload.jsp" >
<INPUT name="filea" type="file"><BR>
<INPUT name="btnval" type="submit" value="上载">
<INPUT type="reset" value="重置">
</FORM>
</body>
</html>
客户端上传后,服务器端的数据流头尾部格式如下,这里上传了一个Word文档
我们看看数据流的头部:
-----------------------------7d22f821706e0Content-Disposition: form-data;
name="filea"; filename="C:\工作流管理系统总体设计.doc"Content-Type:
application/msword
邢唷??...... (注意这里是数据文件开始的地方)
....................................
尾部标志:
-----------------------------7d22f821706e0Content-Disposition: form-data;
name="btnval"
上载-----------------------------7d22f821706e0--
所以去掉头尾部标志性数据我们就得到上传的文件数据了。
下面我们看看处理上传的Bean:uploadBean 首先得到初始化Bean得到上下文环境:
public final void initialize(PageContext pageContext)
throws ServletException
{
m_application = pageContext.getServletContext();
m_request = (HttpServletRequest)pageContext.getRequest();
m_response = (HttpServletResponse)pageContext.getResponse();
}
将数据流写到一个BYTES数组中,数组大小就是REQUEST流的大小。
m_totalBytes = m_request.getContentLength();
m_binArray = new byte[m_totalBytes];
for(; totalRead < m_totalBytes; totalRead += readBytes)
try
{
m_request.getInputStream();
readBytes = m_request.getInputStream().read(m_binArray, totalRead, m_totalBytes - totalRead);
}
catch(Exception e)
{
System.out.println(" Unable to upload data .");
上一页 下一页






