日期:2014-05-19 浏览次数:21132 次
public class ImageServlet extends HttpServlet {
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
MultipartRequest mr = null;
int maxPostSize = 1*100*1024*1024;
String dir = getServletConfig().getServletContext().getRealPath("/uploadImage");
mr = new MultipartRequest(request,dir,maxPostSize,"utf-8");
Enumeration files = mr.getFileNames();
String fileName ="";
String path = "";
while(files.hasMoreElements()){
fileName = files.nextElement().toString();
path = mr.getFilesystemName(fileName);
File f = mr.getFile(fileName);
if(f==null){
throw new ServletException("file is null");
}
Date dt = new Date(System
.currentTimeMillis());
SimpleDateFormat fmt = new SimpleDateFormat(
"yyyyMMddHHmmssSSS");
String time = fmt.format(dt);
String newName = time+f.getName().substring(path.lastIndexOf('.'));
File newFile = new File(dir+"/"+newName);
f.renameTo(newFile);
System.out.println("newName:"+newName);
System.out.println("filename:"+newFile.getName());
System.out.println("path:"+newFile.getPath());
}
PrintWriter out = response.getWriter();
out.print("上传成功!");
}
}