jatarta fileupload 实例

来源:百度文库 编辑:神马文学网 时间:2024/04/24 06:57:57
<%
//1.首先在http://jakarta.apache.org/commons/index.html下载FileUpload和IO的jar包,并放到WEB-INF/lib中;
//2.如下代码:
%>
<%@page contentType="text/html; charset=GBK"%>
<%@page import="java.io.*,java.util.*,org.apache.commons.fileupload.*,org.apache.commons.fileupload.disk.*,org.apache.commons.fileupload.servlet.* "%>


upload


jakarta fileupload test







file:



Txt:






<%
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
Map req = new HashMap();
Map uploadFile = new HashMap();
if (isMultipart) {
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
List items = null; /* FileItem */
try {
items = upload.parseRequest(request);
}
catch (FileUploadException e) {
out.println(e);
}
// Process the uploaded items
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
String name = item.getFieldName();
String value = new String(item.getString().getBytes("ISO8859-1"), "GBK");
req.put(name, value);
}
else {
String fieldName = item.getFieldName();
uploadFile.put(fieldName, item);
}
}
items.clear();
}
if (!isMultipart) {
return;
}
//TEST
//request.getParameter("Txt");
String key = "Txt";
String value = req.get(key).toString();
out.println(key + "=" + value);
//save upload File "file"
FileItem item = (FileItem) uploadFile.get("file1");
out.print(item);
if (item != null) {
String filePath = item.getName(); //全路径文件名
String fileName = filePath.replaceAll("", "/");
fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
File uploadedFile = new File("e:/" + fileName);
try {
item.write(uploadedFile);
}
catch (Exception e) {
}
}
%>