index.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>上传图片</title>
</head>
<body>
<center>
<form action="upload_pic" method="post" enctype="multipart/form-data">
文件:<input type="file" name="pic"/><br/>
描述:<input type="text" name="des"/><br/>
<input type="submit" value="upload"/>
</form>
</center>
</body>
</html>
UploadPictureServlet.java
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
/**
* Servlet implementation class UploadPictureServlet
*/
@MultipartConfig
@WebServlet("/upload_pic")
public class UploadPictureServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String mimes="image/jpeg,image/gif,image/bmp,image/jpg";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=gbk");
PrintWriter out=response.getWriter();
out.println("<html><head><title>文件上传</title></head><body>");
Part part=request.getPart("pic");
System.out.println(part);
if(null!=part){
String mime=part.getContentType();
if(-1==mimes.indexOf(mime.toLowerCase())){
//不是图片
part.delete();
out.println("<script language='javascript'>alert('不是图片')</script>");
}else if(1024*1024*2<part.getSize()){
part.delete();
out.println("<script language='javascript'>alert('图片不能超出2M')</script>");
}else{
String fileName=getFileName(part);
String extName=getExtName(fileName);
long size=part.getSize();
String contentType=part.getContentType();
String path=this.getServletContext().getRealPath("pics");
String newFileName=UUID.randomUUID().toString()+extName;
//存到服务器
part.write(path+File.separator+newFileName);
out.println("<h1>上传成功!!!!</h1><ul>");
out.println("<li>客户端文件名:"+fileName+"</li>");
out.println("<li>ContentType:"+extName+"</li>");
out.println("<li>长度:"+size+"</li>");
out.println("<li>服务器上文件名:"+path+File.separator+newFileName+"</li>");
out.println("</ul>");
}
}
out.println("</body></html>");
out.close();
}
//取得文件扩展名
public String getExtName(String fileName){
String extName=null;
int index=fileName.lastIndexOf(".");
if(-1!=index){
extName=fileName.substring(index);
}
return extName;
}
//取得文件名
public String getFileName(Part part){
String fileName=null;
String hv=part.getHeader("content-disposition");
String pattern="(form-data; name=\"(.*?)\"; filename=\"(.*?)\")";
Matcher match=Pattern.compile(pattern).matcher(hv);
if(match.find()){
fileName=match.group(3);
}
return fileName;
}
}