Javaweb 如何使用 getPart 接收表单文件?

  • 来源:网络
  • 更新日期:2020-07-22

摘要:使用getPart接收表单文件时,注意Tomcat版本要在8之上。前台 : form.jsp<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title<

使用getPart接收表单文件时,注意Tomcat版本要在8之上。

前台 : form.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/test" method="post" enctype="multipart/form-data">
  请选择文件:<input type="file" name="file"><br>
  <input type="submit" value="提交">
</form>
</body>
</html>

后台:TestServlet

@WebServlet(name = "TestServlet", urlPatterns = "/test")
@MultipartConfig
public class TestServlet extends HttpServlet {
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //获取文件,参数为前台的name
    Part part = request.getPart("photo");
    	//判断是否选择了文件
    if (part.getSize() == 0) {
      request.setAttribute("msg", "请选择用户头像");
      request.getRequestDispatcher("/register.jsp").forward(request, response);
      return;	//不再执行后续操作
    }
    //获取文件名,获取到文件名的格式如:a.jpg
    String fileName = part.getSubmittedFileName();
    /**
     截取文件名的后缀名:
     photo.lastIndexOf('.')的返回值为"."的位置,加1表示后缀名的起始位置。
     photo.substring(photo.lastIndexOf('.')+1),表示从后缀名的起始位置截取到结束位置。
     * */
    String fileType = fileName.substring(fileName.lastIndexOf('.') + 1);
    //判断该文件是不是图片格式
    if (!("jpg".equalsIgnoreCase(fileType) || "jpeg".equalsIgnoreCase(fileType) || "png".equalsIgnoreCase(fileType))) {
      //不是图片格式,停止下一步,并将信息反馈给前台页面
      request.setAttribute("msg","上传的文件必须为图片");
      request.getRequestDispatcher("/form.jsp").forward(request, response);
      return;
    }
    //是图片类型,构建一个上传图片的存储路径
    String path = "E:\\\\upload";
    File file = new File(path);
    if (!file.exists()) {
      file.mkdirs(); //创建文件和文件夹
    }
    //将part内容写到文件夹内,生成一个文件
    part.write(path + "/" + fileName);
  }
}

String path = "E:\\\\testPic";设置成本地文件夹路径与Tomcat服务器脱离关联,可以防止文件丢失。但需要将该文件夹挂载到Tomcat服务器。

挂载方式:Eclipse:

1、双击集成在Eclipse中的tomcat服务器

2、点击添加额外的web资源

3、将本地存储上传文件的文件夹添加进来即可!

一定要ctrl + S

IDEA:

优化:将上传图片封装成工具类

UploadUtils.java

public class UploadUtils {
  public static String upload(Part part, HttpServletRequest request, HttpServletResponse response) {
    //获取文件的名称
    String photo = part.getSubmittedFileName();
    //重命名该文件,防止出现重名文件被覆盖的情况
    photo = UUID.randomUUID() + photo;
    /**
     截取文件名的后缀名:
     photo.lastIndexOf('.')的返回值为"."的位置,加1表示后缀名的起始位置。
     photo.substring(photo.lastIndexOf('.')+1),表示从后缀名的起始位置截取到结束位置。
     * */
    String fileType = photo.substring(photo.lastIndexOf('.') + 1);
    //判断该文件是不是图片格式
    if (!("jpg".equalsIgnoreCase(fileType) || "jpeg".equalsIgnoreCase(fileType) || "png".equalsIgnoreCase(fileType))) {
      //不是图片格式,返回空字串
      return "";
    }
    //是图片类型,构建一个上传图片的存储路径,并返回字符串的名称,用于存储到数据库
    String path = "E:\\\\upload";
    File file = new File(path);
    if (!file.exists()) {
      file.mkdirs(); //创建文件和文件夹
    }
    //将part内容写到文件夹内,生成一个文件
    try {
      part.write(path + "/" + photo);
    } catch (IOException e) {
      e.printStackTrace();
    }
    return photo;
  }
}

调用工具类:

@WebServlet(name = "TestServlet", urlPatterns = "/test")
@MultipartConfig
public class TestServlet extends HttpServlet {
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
  //获取文件
  Part part = request.getPart("photo");
  //判断用户是否选择文件,如果没有选择头像,不进行后续操作
  if (part.getSize() == 0) {
    request.setAttribute("msg", "请选择用户头像");
    request.getRequestDispatcher("/register.jsp").forward(request, response);
    return;
  }
  String photo = UploadUtils.upload(part, request, response);
  //判断photo是否为空字符串,为空字符串,说明不是图片类型,也不进行后续操作
  if (photo == "") {
    request.setAttribute("msg", "请选择图片类型的文件,如png,jpg,jpeg");
    request.getRequestDispatcher("/register.jsp").forward(request, response);
    return;
  }
  //不是空字符串,执行后续操作,如将路径存储到数据库等
  ............................................
}

推荐教程:《Java教程》