\n\n  請選擇文件:
\n  \n<\/form>\n<\/body>\n<\/html><\/pre>

后臺:TestServlet<\/p>

@WebServlet(name = \"TestServlet\", urlPatterns = \"\/test\")\n@MultipartConfig\npublic class TestServlet extends HttpServlet {\n  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n    \/\/獲取文件,參數(shù)為前臺的name\n    Part part = request.getPart(\"photo\");\n    \t\/\/判斷是否選擇了文件\n    if (part.getSize() == 0) {\n      request.setAttribute(\"msg\", \"請選擇用戶頭像\");\n      request.getRequestDispatcher(\"\/register.jsp\").forward(request, response);\n      return;\t\/\/不再執(zhí)行后續(xù)操作\n    }\n    \/\/獲取文件名,獲取到文件名的格式如:a.jpg\n    String fileName = part.getSubmittedFileName();\n    \/**\n     截取文件名的后綴名:\n     photo.lastIndexOf('.')的返回值為\".\"的位置,加1表示后綴名的起始位置。\n     photo.substring(photo.lastIndexOf('.')+1),表示從后綴名的起始位置截取到結(jié)束位置。\n     * *\/\n    String fileType = fileName.substring(fileName.lastIndexOf('.') + 1);\n    \/\/判斷該文件是不是圖片格式\n    if (!(\"jpg\".equalsIgnoreCase(fileType) || \"jpeg\".equalsIgnoreCase(fileType) || \"png\".equalsIgnoreCase(fileType))) {\n      \/\/不是圖片格式,停止下一步,并將信息反饋給前臺頁面\n      request.setAttribute(\"msg\",\"上傳的文件必須為圖片\");\n      request.getRequestDispatcher(\"\/form.jsp\").forward(request, response);\n      return;\n    }\n    \/\/是圖片類型,構(gòu)建一個上傳圖片的存儲路徑\n    String path = \"E:\\\\upload\";\n    File file = new File(path);\n    if (!file.exists()) {\n      file.mkdirs(); \/\/創(chuàng)建文件和文件夾\n    }\n    \/\/將part內(nèi)容寫到文件夾內(nèi),生成一個文件\n    part.write(path + \"\/\" + fileName);\n  }\n}<\/pre>

String path = \"E:\\\\testPic\";設(shè)置成本地文件夾路徑與Tomcat服務(wù)器脫離關(guān)聯(lián),可以防止文件丟失。但需要將該文件夾掛載到Tomcat服務(wù)器。<\/p>

掛載方式:Eclipse:<\/p>

1、雙擊集成在Eclipse中的tomcat服務(wù)器<\/p>

\"How<\/p>

2、點擊添加額外的web資源<\/p>

\"How<\/p>

3、將本地存儲上傳文件的文件夾添加進(jìn)來即可!<\/p>

\"How<\/p>

一定要ctrl + S<\/p>

IDEA:<\/p>

\"How<\/p>

\"How<\/p>

優(yōu)化:將上傳圖片封裝成工具類<\/p>

UploadUtils.java<\/p>

public class UploadUtils {\n  public static String upload(Part part, HttpServletRequest request, HttpServletResponse response) {\n    \/\/獲取文件的名稱\n    String photo = part.getSubmittedFileName();\n    \/\/重命名該文件,防止出現(xiàn)重名文件被覆蓋的情況\n    photo = UUID.randomUUID() + photo;\n    \/**\n     截取文件名的后綴名:\n     photo.lastIndexOf('.')的返回值為\".\"的位置,加1表示后綴名的起始位置。\n     photo.substring(photo.lastIndexOf('.')+1),表示從后綴名的起始位置截取到結(jié)束位置。\n     * *\/\n    String fileType = photo.substring(photo.lastIndexOf('.') + 1);\n    \/\/判斷該文件是不是圖片格式\n    if (!(\"jpg\".equalsIgnoreCase(fileType) || \"jpeg\".equalsIgnoreCase(fileType) || \"png\".equalsIgnoreCase(fileType))) {\n      \/\/不是圖片格式,返回空字串\n      return \"\";\n    }\n    \/\/是圖片類型,構(gòu)建一個上傳圖片的存儲路徑,并返回字符串的名稱,用于存儲到數(shù)據(jù)庫\n    String path = \"E:\\\\upload\";\n    File file = new File(path);\n    if (!file.exists()) {\n      file.mkdirs(); \/\/創(chuàng)建文件和文件夾\n    }\n    \/\/將part內(nèi)容寫到文件夾內(nèi),生成一個文件\n    try {\n      part.write(path + \"\/\" + photo);\n    } catch (IOException e) {\n      e.printStackTrace();\n    }\n    return photo;\n  }\n}<\/pre>

調(diào)用工具類:<\/p>

@WebServlet(name = \"TestServlet\", urlPatterns = \"\/test\")\n@MultipartConfig\npublic class TestServlet extends HttpServlet {\n  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{\n  \/\/獲取文件\n  Part part = request.getPart(\"photo\");\n  \/\/判斷用戶是否選擇文件,如果沒有選擇頭像,不進(jìn)行后續(xù)操作\n  if (part.getSize() == 0) {\n    request.setAttribute(\"msg\", \"請選擇用戶頭像\");\n    request.getRequestDispatcher(\"\/register.jsp\").forward(request, response);\n    return;\n  }\n  String photo = UploadUtils.upload(part, request, response);\n  \/\/判斷photo是否為空字符串,為空字符串,說明不是圖片類型,也不進(jìn)行后續(xù)操作\n  if (photo == \"\") {\n    request.setAttribute(\"msg\", \"請選擇圖片類型的文件,如png,jpg,jpeg\");\n    request.getRequestDispatcher(\"\/register.jsp\").forward(request, response);\n    return;\n  }\n  \/\/不是空字符串,執(zhí)行后續(xù)操作,如將路徑存儲到數(shù)據(jù)庫等\n  ............................................\n}<\/pre>

推薦教程:《Java教程<\/a>》<\/p>"}

亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

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>

后臺:TestServlet

@WebServlet(name = "TestServlet", urlPatterns = "/test")
@MultipartConfig
public class TestServlet extends HttpServlet {
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //獲取文件,參數(shù)為前臺的name
    Part part = request.getPart("photo");
    	//判斷是否選擇了文件
    if (part.getSize() == 0) {
      request.setAttribute("msg", "請選擇用戶頭像");
      request.getRequestDispatcher("/register.jsp").forward(request, response);
      return;	//不再執(zhí)行后續(xù)操作
    }
    //獲取文件名,獲取到文件名的格式如:a.jpg
    String fileName = part.getSubmittedFileName();
    /**
     截取文件名的后綴名:
     photo.lastIndexOf(&#39;.&#39;)的返回值為"."的位置,加1表示后綴名的起始位置。
     photo.substring(photo.lastIndexOf(&#39;.&#39;)+1),表示從后綴名的起始位置截取到結(jié)束位置。
     * */
    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;
    }
    //是圖片類型,構(gòu)建一個上傳圖片的存儲路徑
    String path = "E:\\upload";
    File file = new File(path);
    if (!file.exists()) {
      file.mkdirs(); //創(chuàng)建文件和文件夾
    }
    //將part內(nèi)容寫到文件夾內(nèi),生成一個文件
    part.write(path + "/" + fileName);
  }
}

String path = "E:\\testPic";設(shè)置成本地文件夾路徑與Tomcat服務(wù)器脫離關(guān)聯(lián),可以防止文件丟失。但需要將該文件夾掛載到Tomcat服務(wù)器。

掛載方式:Eclipse:

1、雙擊集成在Eclipse中的tomcat服務(wù)器

How does Javaweb use getPart to receive form files?

2、點擊添加額外的web資源

How does Javaweb use getPart to receive form files?

3、將本地存儲上傳文件的文件夾添加進(jìn)來即可!

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?

優(yōu)化:將上傳圖片封裝成工具類

UploadUtils.java

public class UploadUtils {
  public static String upload(Part part, HttpServletRequest request, HttpServletResponse response) {
    //獲取文件的名稱
    String photo = part.getSubmittedFileName();
    //重命名該文件,防止出現(xiàn)重名文件被覆蓋的情況
    photo = UUID.randomUUID() + photo;
    /**
     截取文件名的后綴名:
     photo.lastIndexOf(&#39;.&#39;)的返回值為"."的位置,加1表示后綴名的起始位置。
     photo.substring(photo.lastIndexOf(&#39;.&#39;)+1),表示從后綴名的起始位置截取到結(jié)束位置。
     * */
    String fileType = photo.substring(photo.lastIndexOf(&#39;.&#39;) + 1);
    //判斷該文件是不是圖片格式
    if (!("jpg".equalsIgnoreCase(fileType) || "jpeg".equalsIgnoreCase(fileType) || "png".equalsIgnoreCase(fileType))) {
      //不是圖片格式,返回空字串
      return "";
    }
    //是圖片類型,構(gòu)建一個上傳圖片的存儲路徑,并返回字符串的名稱,用于存儲到數(shù)據(jù)庫
    String path = "E:\\upload";
    File file = new File(path);
    if (!file.exists()) {
      file.mkdirs(); //創(chuàng)建文件和文件夾
    }
    //將part內(nèi)容寫到文件夾內(nèi),生成一個文件
    try {
      part.write(path + "/" + photo);
    } catch (IOException e) {
      e.printStackTrace();
    }
    return photo;
  }
}

調(diào)用工具類:

@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");
  //判斷用戶是否選擇文件,如果沒有選擇頭像,不進(jìn)行后續(xù)操作
  if (part.getSize() == 0) {
    request.setAttribute("msg", "請選擇用戶頭像");
    request.getRequestDispatcher("/register.jsp").forward(request, response);
    return;
  }
  String photo = UploadUtils.upload(part, request, response);
  //判斷photo是否為空字符串,為空字符串,說明不是圖片類型,也不進(jìn)行后續(xù)操作
  if (photo == "") {
    request.setAttribute("msg", "請選擇圖片類型的文件,如png,jpg,jpeg");
    request.getRequestDispatcher("/register.jsp").forward(request, response);
    return;
  }
  //不是空字符串,執(zhí)行后續(xù)操作,如將路徑存儲到數(shù)據(jù)庫等
  ............................................
}

推薦教程:《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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

PHP Tutorial
1488
72
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

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].

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.

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.

How to receive Tencent news on WeChat How to receive Tencent news on WeChat Mar 18, 2024 pm 11:40 PM

WeChat has built-in Tencent News function, so you can get news information at any time without downloading the Tencent News app separately. This has also become the main way for many users to obtain fresh information in their daily use. So, many users who want to open it but don’t know how to open it, how can they enable and receive Tencent News in WeChat? Below, the editor of this website will bring you a detailed introduction to the content strategy, hoping to help everyone in need. First open the phone, enter the software and click the &quot;Me&quot; menu. Now click the &quot;Settings&quot; icon. In the pop-up dialog box, click the &quot;General&quot; function. Now select the accessibility function and come to the function list of the software. Click &quot;Tencent News&quot; to enable the function. Click now to follow Tencent News and receive Tencent news every day.

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

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

See all articles