1.myapp/index.html
<html>
<head>
文件操作
<iframe id="iframefile" scrolling="no" frameborder="0" width="100%" src="/myapp/fileUpload.jsp"></iframe>
</head>
</html>
2.myapp/fileUpload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page import="test.UploadServlet"%>
<%@ page import="java.io.File"%>
<%@ page import="java.io.FileInputStream"%>
<%@ page import="java.net.URLEncoder"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传</title>
</head>
<%
String cztype=request.getParameter("cztype");//操作类型
if(cztype!=null && cztype.equals("del")){ //文件删除
String temppath = request.getParameter("path");
if(temppath!=null && !temppath.equals("")){
File file = new File(temppath);
file.delete();
}
}
if(cztype!=null && cztype.equals("down")){ //文件下载
String downpath=request.getParameter("path");
String filename=request.getParameter("filename");
//String filename=new String(request.getParameter("filename").getBytes("ISO8859-1"),"UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("application/x-download");
response.addHeader("Content-Disposition","attachment;filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\"");
try{
java.io.OutputStream os = response.getOutputStream();
java.io.FileInputStream fis = new FileInputStream(downpath);
byte[] b = new byte[1024];
int i=0;
while((i=fis.read(b))>0){
os.write(b,0,i);
}
os.flush();
os.close();
fis.close();
out.clear();
out = pageContext.pushBody();
}catch(Exception e){
e.printStackTrace();
}
}
String path = getServletContext().getRealPath("") + "//uploadFolder//";
File filepath = new File(path);
File[] fileArray = filepath.listFiles();
%>
<body leftmargin=0 rightmargin=0 topmargin=0>
<form method = "post" id = "upload" action ="/myapp/servlet/UploadServlet" enctype="multipart/form-data">
<table width="100%" border="1">
<tr><td height="20" colspan="2">附件上传(下载时请右键"目标另存为")</td></tr>
<tr><td width="50%">文件名</td><td width="50%">操作</td></tr>
<%
int height = 3; //默认表格行数
if(fileArray!=null){
height += fileArray.length;
for(int i=0;i<fileArray.length;i++){
File file = fileArray[i];
String urlpath="http://"+request.getLocalAddr()+":"+request.getLocalPort()+"/myapp/uploadFolder/"+file.getName();
%>
<tr><td><a href="/myappp/fileUpload.jsp?cztype=down&path=<%=URLEncoder.encode(file.getAbsolutePath(),"utf-8")%>&filename=<%=URLEncoder.encode(file.getName(),"utf-8")%>") target="_blank"><%=file.getName()%></a></td><td><a href="/myapp/fileUpload.jsp?cztype=del&path=<%=file.getAbsolutePath()%>">删除</a></td></tr>
<%}
}
%>
<p>
<tr>
<td><input type = "file" id = "uploadFile" name = "uploadFile"></td>
<td><input type = "button" onclick="if(upload.uploadFile.value==null || upload.uploadFile.value=='') alert('请选择文件!'); else upload.submit();" value = "上传"></td>
</tr>
</table>
</form>
<input type="hidden" name="fileuploadheight" value="<%=height%>">
</body>
<script>
window.parent.document.getElementById("iframefile").style.height=document.all("fileuploadheight").value * 20 + 20; //自动调整iframe大小
</script>
</html>
3.myapp/WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>
test.UploadServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/servlet/UploadServlet</url-pattern>
</servlet-mapping>
</web-app>
4.test.UploadServlet
package test;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadServlet extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Map parameters = new HashMap();
try {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fu = new ServletFileUpload(factory);
fu.setHeaderEncoding("UTF-8");
fu.setSizeMax(4194304);
// 得到所有的文件,以及其它请求参数:
List fileItems = fu.parseRequest(request);
Iterator i = fileItems.iterator();
// 依次处理每一个文件,以及请求参数:
while(i.hasNext()) {
FileItem fi = (FileItem)i.next();
// 如果是文件项,则保存文件到上传目录
if (!fi.isFormField()) {
// 获得文件名,这个文件名包括路径:
String fileName = fi.getName();
long filesize = fi.getSize();
System.out.println("上传的文件名为!!!"+fileName + " size : " + filesize);
// 写入文件
fileName = fileName.substring(fileName.lastIndexOf("\\"));
String conPath = getServletContext().getRealPath("");
File filepath= new File(conPath + "//uploadFolder//");
File file = new File(filepath+"//"+fileName);
if(!filepath.exists()){
filepath.mkdir();
}
if(file.exists()){
file.delete();
}
fi.write(file);
}
else { //如果是请求参数,则保存到HashMap中
String name = fi.getFieldName();
String value = fi.getString();
parameters.put(name, value);
System.out.println(parameters);
}
}
response.sendRedirect("/myapp/fileUpload.jsp");
}
catch(Exception ex) {
System.out.println("上传文件时出错!!!");
ex.printStackTrace();
}
}
}
5.myapp/WEB-INF/classes/commons-fileupload-1.2.1.jar
6.myapp/WEB-INF/classes/commons-io-1.4.jar