@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//获取文件部件part
Part part=req.getPart("file");
//获取请求信息
String name=part.getHeader("content-disposition");
//得到上传文件保存的路径
String root=req.getServletContext().getRealPath("/upload");
//得到上传文件的后缀名
String str=name.substring(name.lastIndexOf("."),name.length()-1);
//生成一个随机的文件名
String fileName=root+"\\"+UUID.randomUUID().toString()+str;
//保存文件
part.write(fileName);
}
}
servlet3.0上传文件
原文:http://my.oschina.net/nly/blog/345183