package uploaddemo;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.*;
public class UploadServlet extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=GBK";
DiskFileItemFactory dfif = new DiskFileItemFactory();
ServletFileUpload sfu = new ServletFileUpload(dfif);
File uploadDir = null;
//Initialize global variables
public void init() throws ServletException {
uploadDir = new File(getServletContext().getRealPath("/WEB-INF/files"));
if(!uploadDir.exists())
{
uploadDir.mkdir();
}
}
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
List fileItems = null;
try {
fileItems = sfu.parseRequest(request);
} catch (FileUploadException ex) {
throw new ServletException(ex);
}
Iterator it = fileItems.iterator();
while (it.hasNext()) {
FileItem item = (FileItem) it.next();
if ( item.isFormField() ) {// 普通的字段
System.out.println("处理普通字段:");
System.out.println(item.getFieldName() + " = " + item.getString("GBK") );
} else {// 文件
// 获取文件名
String fn = item.getName();
int lostSeparatorIndex = fn.lastIndexOf(File.separator);
if (lostSeparatorIndex>=0) {
fn = fn.substring( lostSeparatorIndex+1 );
}
// 确定保存路径
File f = new File(uploadDir, fn);
try {
item.write(f);
} catch (Exception ex) {
throw new ServletException(ex);
}
System.out.println("处理上传的文件:");
System.out.println("原文件名称:"+item.getName());
System.out.println("现存储路径:"+f.getAbsolutePath());
}
}
out.println("<html>");
out.println("<head><title>UploadServlet</title></head>");
out.println("<body bgcolor=\"#ffffff\">");
out.println("<p>上传成功</p>");
out.println("</body>");
out.println("</html>");
out.close();
}
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response);
}
//Clean up resources
public void destroy() {
}
}
评论0