servlet3.0获取参数与文件上传代码示例

转:

servlet3.0获取参数与文件上传代码示例

  1. package com.igeek.servlet;
  2.  
  3. import java.io.IOException;
  4. import java.util.Collection;
  5.  
  6. import javax.servlet.ServletException;
  7. import javax.servlet.annotation.MultipartConfig;
  8. import javax.servlet.annotation.WebServlet;
  9. import javax.servlet.http.HttpServlet;
  10. import javax.servlet.http.HttpServletRequest;
  11. import javax.servlet.http.HttpServletResponse;
  12. import javax.servlet.http.Part;
  13.  
  14. import org.apache.catalina.core.ApplicationPart;
  15.  
  16. /**
  17. * Servlet implementation class AddUserServlet
  18. */
  19. @WebServlet("/addUser")
  20. @MultipartConfig // 该servlet要接收文件上传
  21. public class AddUserServlet extends HttpServlet {
  22. private static final long serialVersionUID = 1L;
  23.  
  24. /**
  25. * @see HttpServlet#HttpServlet()
  26. */
  27. public AddUserServlet() {
  28. super();
  29. // TODO Auto-generated constructor stub
  30. }
  31.  
  32. /**
  33. * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  34. */
  35. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  36. //普通请求参数获取
  37. String uname = request.getParameter("uname");
  38. String upass = request.getParameter("upass");
  39. System.out.println("uname="+uname+";upass="+upass);
  40. //获取文件
  41. Collection<Part> parts = request.getParts();
  42. //遍历取出文件
  43. for (Part part : parts) {
  44. System.out.println("-----------------------");
  45. if(part.getHeader("Content-Disposition").contains("filename")){
  46. String fileName = part.getHeader("Content-Disposition");
  47. fileName = fileName.substring(fileName.indexOf("filename=\"")+10, fileName.lastIndexOf("\""));
  48. String name = request.getParameter("head");
  49. System.out.println(name);
  50. //存储文件 利用part的api将临时文件写入目标文件
  51. part.write("d:/"+fileName);
  52. }
  53. System.out.println("-----------------------");
  54. }
  55. }
  56.  
  57. /**
  58. * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  59. */
  60. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  61. // TODO Auto-generated method stub
  62. doGet(request, response);
  63. }
  64.  
  65. }

 

posted @ 2019-03-20 15:53  戈博折刀  阅读(392)  评论(0编辑  收藏  举报