Home Java JavaBase How does Javaweb use getPart to receive form files?

How does Javaweb use getPart to receive form files?

Jul 22, 2020 pm 05:45 PM
javaweb take over

How does Javaweb use getPart to receive form files?

使用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>
Copy after login

后台: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(&#39;.&#39;)的返回值为"."的位置,加1表示后缀名的起始位置。
     photo.substring(photo.lastIndexOf(&#39;.&#39;)+1),表示从后缀名的起始位置截取到结束位置。
     * */
    String fileType = fileName.substring(fileName.lastIndexOf(&#39;.&#39;) + 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);
  }
}
Copy after login

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

挂载方式:Eclipse:

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

How does Javaweb use getPart to receive form files?

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

How does Javaweb use getPart to receive form files?

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

How does Javaweb use getPart to receive form files?

一定要ctrl + S

IDEA:

How does Javaweb use getPart to receive form files?

How does Javaweb use getPart to receive form files?

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

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(&#39;.&#39;)的返回值为"."的位置,加1表示后缀名的起始位置。
     photo.substring(photo.lastIndexOf(&#39;.&#39;)+1),表示从后缀名的起始位置截取到结束位置。
     * */
    String fileType = photo.substring(photo.lastIndexOf(&#39;.&#39;) + 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;
  }
}
Copy after login

调用工具类:

@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;
  }
  //不是空字符串,执行后续操作,如将路径存储到数据库等
  ............................................
}
Copy after login

推荐教程:《Java教程

The above is the detailed content of How does Javaweb use getPart to receive form files?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to Analyze Code Auditing in Java Web Security How to Analyze Code Auditing in Java Web Security May 16, 2023 am 08:04 AM

1. JavaWeb Security Basics 1. What is code auditing? In layman’s terms, Java code auditing is to discover security issues in the Java application itself by auditing Java code. Since Java itself is a compiled language, even if there are only class files We can still audit Java code. For uncompiled Java source code files, we can read the source code directly, but for compiled class or jar files, we need to decompile them. Java code auditing itself is not very difficult. As long as you are proficient in the auditing process and common vulnerability auditing techniques, you can complete the code auditing work relatively easily. But the way of Java code auditing is not just to use

Is rx receiving or transmitting? Is rx receiving or transmitting? Feb 20, 2023 pm 02:53 PM

rx refers to reception, which corresponds to TX (referring to output); TRX is the transceiver unit in communication, and TX and RX are the two parts of TRX; they appear in pairs in optical fiber, and the transceiver and transceiver are a pair, and the transceiver and transceiver must be at the same time. If you only receive but not send, there is a problem if you only send but not receive.

How to receive verification code with virtual number How to receive verification code with virtual number Oct 31, 2019 pm 04:52 PM

How to receive the verification code with a virtual number: first enter the Yima verification code receiving platform; then register as a website member; then open the SMS verification code service and select the operator; finally obtain the virtual mobile phone number and go to the platform where the verification code is to be sent. Fill in your mobile phone number and select [Send Verification Code].

what is javaweb what is javaweb Aug 09, 2023 am 11:50 AM

Javaweb is a technology framework for developing web applications that combines the Java programming language with web development technology to provide an efficient, secure and reliable way to build and deploy web applications. It has powerful functions, flexibility and cross-platform nature, and is widely used in websites and enterprise-level systems of all sizes.

Summary of methods for implementing email sending and receiving functions using PHP email functions Summary of methods for implementing email sending and receiving functions using PHP email functions Nov 20, 2023 pm 02:18 PM

Summary of methods for implementing email sending and receiving functions using PHP email functions. With the popularity of the Internet, email has become one of the indispensable communication tools in people's daily lives. In website development, it is often necessary to implement the function of sending and receiving emails. As a commonly used server-side scripting language, PHP provides a series of powerful email functions that can easily send and receive emails. Mail sending function PHP provides the mail() function to implement the mail sending function. The following is sent using the mail() function

How to use JavaWeb to display mysql database data How to use JavaWeb to display mysql database data Jun 01, 2023 am 09:49 AM

EMS-Employee Information Management System MySQL learning basic operation summary MySQL learning basic command practical summary create ems database showdatabases; createdatabaseems; useems; create user table createtableuser(idintprimarykeyauto_increment, namevarchar(50), salarydouble, ageint); insert table data insertintouservalues (1,'zs',3000,20);insertintouser

Email sending and receiving -- integrating email functions in web applications Email sending and receiving -- integrating email functions in web applications Sep 12, 2023 pm 06:12 PM

Sending and receiving emails - Integrating email functions in web applications With the popularity of the Internet, email has become an indispensable part of people's lives and work. With the development of Web applications, integrating email functions into Web applications has become an increasingly popular requirement. This article will introduce how to implement the sending and receiving functions of emails in web applications. Part 1: Integration of the email sending function To implement the email sending function, you need to consider the following steps: To set up the email server to send emails in a web application, you first need to

How to solve the problem of sending and receiving emails in PHP development How to solve the problem of sending and receiving emails in PHP development Jun 30, 2023 pm 01:57 PM

How to deal with email sending and receiving issues in PHP development In web application development, email transmission is a very important function, especially in the process of interacting with users and transmitting information. PHP, as a popular server-side scripting language, provides us with various functions and solutions for processing emails. This article will introduce how to handle email sending and receiving issues in PHP development. Sending emails 1. Use SMTP server to send emails. SMTP (Simple Mail Transfer Protocol) is a standard for sending emails.

See all articles