O'Reilly cos上传组件的使用(2/3) - 获取文件信息
upload.html:
<form method="post" action="cos.jsp"
enctype="multipart/form-data">
文件1:<input type="file" name="file1" />
说明:<input type="text" name="file1_desc" />
<br />
文件2:<input type="file" name="file2" />
说明:<input type="text" name="file2_desc" />
<input type="submit" value="上传" />
</form>
cos.jsp:
<%@page contentType="text/html;charset=GBK"%>
<%@page import="com.oreilly.servlet.MultipartRequest"%>
<%@page import="java.io.File,javax.servlet.ServletContext"%>
<%@page import="java.util.Enumeration,java.io.IOException"%>
O'Reilly cos上传组件的使用(2/3) - 获取文件信息<br />
<%
/*设置上传文件路径*/
ServletContext context = getServletContext();
String realPath = context.getRealPath("/");
String saveDir = realPath + "ch9\\fileupload\\upload\\";
//out.println(saveDir + "<br />");//输出实际路径
File dir = new File(saveDir);
if(!dir.exists())
dir.mkdirs();
int maxPostSize = 1*1024*1024;//1MB
String encoding = "GBK";
MultipartRequest multi = null;
try{
multi = new MultipartRequest(request ,
saveDir , maxPostSize , encoding);
}catch(IOException e){
//上传大小超过maxPostSize就会出现IOException
out.println(e.getMessage());
return;
}
//至此文件已经上传完成!
//以下为获取上传文件的信息,并不是必需的。
%>
<%
//获取文件信息
Enumeration fileNames = multi.getFileNames();
while(fileNames.hasMoreElements()){
//指表单中的name值
String name = (String)fileNames.nextElement();
String sysname = multi.getFilesystemName(name);
String type = multi.getContentType(name);
out.println("Request Name:" + name +"<br />");
out.println("getFilesystemName:" +
saveDir + sysname +"<br />");
out.println("ContentType:" + type +"<br /><br />");
}
out.println("==========<br />");
%>
<%
//获取文件描述
Enumeration params = multi.getParameterNames();
while(params.hasMoreElements()){
String param = (String)params.nextElement();
String value = multi.getParameter(param);
out.println("Param Name:" + param +"<br />");
out.println("Param Value:" + value +"<br /><br />");
}
out.println("==========<br />");
%>
<%
//将前面两个组合起来:获取文件及文件描述
//<input type="file" name="file1" />
//<input type="text" name="file1_desc" />
String descExt = "_desc";
Enumeration files = multi.getFileNames();
while(files.hasMoreElements()){
String name = (String)files.nextElement();
String sysname = multi.getFilesystemName(name);
String type = multi.getContentType(name);
String desc = multi.getParameter(name + descExt);
out.println("Request Name:" + name +"<br />");
out.println("getFilesystemName:" +
saveDir + sysname +"<br />");
out.println("ContentType:" + type +"<br />");
out.println("Description:" + desc + "<br /><br />");
}
%>