package cn.gdpe.upload;
import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.oreilly.servlet.MultipartRequest;
public class UploadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("--- BEGIN DOPOST ---");
HttpSession session = request.getSession();
String uploadDir = "photoFile/";
String ctxDir = session.getServletContext().getRealPath(String.valueOf("/"));
if (!ctxDir.endsWith(String.valueOf("/"))) {
ctxDir = ctxDir + "/";
}
File savePath = new File(ctxDir + uploadDir);
if (!savePath.exists()) {
savePath.mkdirs();
}
System.out.println(savePath.getName()+"======");
String saveDirectory = ctxDir + uploadDir;
int maxPostSize = 80 * 1024 * 1024;
String encoding = "UTF-8";
MultipartRequest multi = null;
try {
multi = new MultipartRequest(request, saveDirectory, maxPostSize, encoding);
} catch (IOException e) {
e.printStackTrace();
return;
}
@SuppressWarnings("rawtypes")
//传回所有文件输入类型的名称
Enumeration files = multi.getFileNames();
while (files.hasMoreElements()) {
String name = (String) files.nextElement();
File f = multi.getFile(name);
System.out.println(f.getName());
if (f != null) {
String fileName = multi.getFilesystemName(name);
String lastFileName = saveDirectory + "/" + fileName;
String fileSavePath = uploadDir + fileName;
System.out.println("SimpleUploaderServlet");
System.out.println("绝对路径:" + lastFileName);
System.out.println("相对路径:" + fileSavePath);
response.getWriter().print(fileSavePath);
response.getWriter().println(" ");
}
}
System.out.println("--- END DOPOST ---");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request,response);
}
}