@WebServlet(“/ajaxUpload”)
@MultipartConfig //开启上传功能
public class FileUploadServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding(“utf-8”);
//获取用户名
String userName=req.getParameter(“userName”);
//获取年龄
String age=req.getParameter(“age”);
System.out.println(userName);
System.out.println(age);
//获取项目部署的绝对路径
String uploadPath=req.getServletContext().getRealPath(“/photos”);
//构建上传的文件夹
File dir=new File(uploadPath);
if(!dir.exists()){
dir.mkdir();
}
//获取所有上传的Part
Collection<Part> parts=req.getParts();
for (Part part:parts) {
//判断上传的类型是否为空,如果为空则不执行上传
if(part.getContentType()!=null){
//获取文件名
String fileName=part.getSubmittedFileName();
//执行上传
part.write(uploadPath+File.separator+fileName);
}
}
//响应上传成功
resp.getWriter().println(“uplaod success”);
}
}