Fileupload-1.2.1使用简单样例

时间:2023-11-22 13:20:50

在測试本例至少须要在web程序的WEB-INF/lib下包括commons-fileupload- 1.2.1和commons-io-1.3.2两个类库。

fileupload.jsp

<%@ page contentType="text/html; charset=gb2312" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>
<%@ page import="org.apache.commons.io.*" %>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.disk.*" %>
<%@ page import="org.apache.commons.fileupload.servlet.*" %>
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>文件传输样例</title>
</head>

<body>
<%
boolean isMultipart = ServletFileUpload.isMultipartContent(request);//检查表单中是否包括文件
if(isMultipart){
FileItemFactory factory = new DiskFileItemFactory();
//factory.setSizeThreshold(yourMaxMemorySize); 此处可设置使用的内存最大值
//factory.setRepository(yourTempDirectory); 文件暂时文件夹

ServletFileUpload upload = new ServletFileUpload(factory);
//upload.setSizeMax(yourMaxRequestSize);同意的最大文件尺寸

List items = upload.parseRequest(request);
for(int i=0;i<items.size();i++){
FileItem fi = (FileItem)items.get(i);
if(fi.isFormField()){//假设是表单字段
%>
<%=fi.getFieldName()%>:<%=fi.getString("GB2312")%><BR>
<%
}else{//假设是文件
DiskFileItem dfi = (DiskFileItem)fi;
if(!dfi.getName().trim().equals("")){//getName()返回文件名,假设是空字符串,说明没有选择文件。
%>
文件被上传到服务上的实际位置:<%=new File(application.getRealPath("/file")+System.getProperty("file.separator")+

FilenameUtils.getName(dfi.getName())).getAbsolutePath()%><br>

<%
dfi.write(new File(application.getRealPath("/file")+System.getProperty("file.separator")+

FilenameUtils.getName(dfi.getName())));
}
}
}
}

%>
</body>
</html>

Index.html

<HTML>
<HEAD>
<META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=gb2312">
<TITLE>commons-fileupload-1.2.1实现文件上传</TITLE>
</HEAD>
<BODY>
<P>commons-fileupload-1.2.1实现文件上传</P>

<FORM NAME="fileupload" ACTION="fileupload.jsp" method="POST" ENCTYPE="multipart/form-data">
<!--必须指定表单的加密类型为 multipart/form-data -->
<P>名称:<INPUT TYPE=TEXT NAME="name" SIZE=12 value="小明"></P>
<P>性别:<INPUT TYPE=TEXT NAME="sex" SIZE=12 value="男"></P>
<P>年龄:<INPUT TYPE=TEXT NAME="age" SIZE=12 value="28"></P>
<P>文件:<INPUT TYPE=FILE NAME="file" SIZE=12></P>
<P><INPUT TYPE=SUBMIT NAME="submit" VALUE="确定"></P>
</FORM>
</BODY>
</HTML>