在JSP中使用Commons FileUpload上载文件
Commons fileUpload 是在JSP中使用的上传文件的组件,现在已经成为Apache项目的一部分。本例简单的说明如何使用 Commons fileUplad 上载文件,首先你要去下载这个组件,放在自己工程的 WEB-INF\lib 下。
第一个文件file.html:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<link href="css/common.css" rel="stylesheet" type="text/css" >
<title>文件传输例子</title>
</head>
<body>
<BR><BR><BR><BR>
<BR><BR><BR><BR>
<center>
<p>本例使用commonfileupload组件上传文件,上传的文件放在file目录下。</p>
<form method="POST" action="upfile.jsp" ENCTYPE="multipart/form-data">
文件:<input type="file" name="file"><input type="submit" value="上传" name="submit">
</form>
</center>
</body>
</html>
注意上面的form的ENCTYPE是multipart/form-data。
第二个文件,upfile.jsp接收文件,通过UUID随机产生一个文件名,把文件放在工程目录下的file目录里面,这个file目录要事先存在,和WEB-INF同级。
<%@ page contentType="text/html; charset=gb2312" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.text.*" %>
<%@ page import="java.sql.*" %>
<%@ page import="javax.sql.*" %>
<%@ page import="javax.naming.*" %>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.servlet.*" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<link href="css/common.css" rel="stylesheet" type="text/css" >
<title>文件传输例子</title>
</head>
<body>
<%
boolean ret = true;
String fname = UUID.randomUUID().toString();
DiskFileUpload upload = new DiskFileUpload();
Iterator it= upload.parseRequest(request).iterator();
while(it.hasNext()){
FileItem fileitem=(FileItem)it.next();
if(!fileitem.isFormField()){
try{
fileitem.write(new File(application.getRealPath("/file")+System.getProperty("file.separator")+fname));
}catch(Exception e){
ret = false;
System.out.print(e);
}
}
}
%>
<center>
<BR><BR>
<%
if(ret) {
out.print("文件传输成功!文件重命名为:"+fname);
}else{
out.print("文件传输失败!");
}
%>
</center>
</body>
</html>







