JSP文件中的上传功能(JSP中的相对路径)------JSP
upload.html页面
<html>
<head>
<title>File Upload</title>
<meta http-equiv="Content-Type" content="text/html; charset="gb2315">
</head>
<body>
<H2>上传文件</H2>
<form enctype="multipart/form-data" method="post" action="upload.jsp">
<p>上传文件1: <input type="file"name="File1" size="20" maxlength="20"> <br>
文件描述 : <input type="text" name="File1" size="30" maxlength="50"> </p>
<p>上传文件2: <input type="file" name="File2" size="20" maxlength="20"> <br>
文件描述 : <input type="text" name="File2" size="30" maxlength="50"> </p>
<input type="submit"value="上传"></p>
</form>
</body>
</html>
upload.jsp页面
<%@page pageEncoding="gb2312"%>
<%@page contentType="text/html; charset=gb2312"%>
<%request.setCharacterEncoding("gb2312");%>
<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>
<%@ page import="com.oreilly.servlet.MultipartRequest" %>
<%
//得到此源文件的目录.
//String strAbsPath=application.getRealPath(request.getRequestURI());
//out.println(strAbsPath);下面是得到相对路径的方法
String s1=new File(new File(new File(application.getRealPath(request.getRequestURI())).getParent()).getParent()).getParent();
%>
<%
// 将上传文件存放在strParentPath
String saveDirectory=s1+"\\uploadfile"+"\\Upload";
//out.println(saveDirectory);
File uploadPath=new File(saveDirectory);
if(!uploadPath.exists()) uploadPath.mkdir();
// 上传文件的大小限制在5 MB
int maxPostSize = 5 * 1024 * 1024 ;
// 存放文件描述
String fileDescription[] = {null,null};
// 上传文件名
String fileName = null;
// 上传文件数
int count = 0 ;
// 上传文件
MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize,"GBK" );
%>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<%
// 取得文件描述
if ( multi.getParameter("File1") != null )
{
fileDescription[0] = multi.getParameter("File1");
}
else
{
fileDescription[0] = "";
}
if ( multi.getParameter("File2") != null )
{
fileDescription[1] = multi.getParameter("File2");
}
else
{
fileDescription[1] = "";
}
// 取得所有上传文件名称
Enumeration filesname = multi.getFileNames();
while (filesname.hasMoreElements())
{
String name = (String) filesname.nextElement();
fileName = multi.getFilesystemName(name);
File f = multi.getFile(name);
String ContentType = multi.getContentType(name);
if (fileName != null)
{
count ++;
%>
<font color="red">您上传的第<%= count %>个文件:</font><br>
文件名:<%= fileName %><br>
文件类型:<%= ContentType %><br>
文件描述:<%= fileDescription[count-1] %><br><br>
<%
} // end if
} // end while
%>
您共上传<font color="red"><%= count %></