Xiaobaixiang: upload files to the server using request.getPart() in the web

It was a day when I was overwhelmed by file uploads. Sure enough, the paths and various settings in the web are really annoying = =

The following is a super white, and its concise "detailed" explanation

 

1. Clear purpose:

  The user uploads the 1.txt file to the server (a folder under the web project)

 

2. Define the process

  The file upload process involves two files, a .jsp file, and a servlet file.

  .jsp file (upload.jsp): user action page = text box showing file name + file selection button (browse...) + confirm upload button

  servlet file (uploadServlet.java): Handle file upload according to the file selected in .jsp

 

3. Start typing the code (lift the table!)

.jsp file

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File upload</title>
</head>
<body>    
<form action="upload.do" enctype="multipart/form-data" method="post"> //关键句1
    <table>
    <tr> <td>Filename:</td>
          <td><input type="file" name="fileName" size="30" /></td> //关键句2
    </tr>
    <tr>
         <td><input type="submit" value="上传" /></td>
    </tr>
    </table>
</form>
</body>
</html>

  Key statements in .jsp:

  Key sentence 1: <form action="upload.do"  enctype="multipart/form-data"  method="post"> //The data in the form is transmitted with binary data, which can transmit text, pictures, etc. .

  Key sentence 2: <input  type="file"  name="fileName" size="30" /> //type set to "file" is the file selection button, which automatically generates a text box + selection button

 

 servlet file:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@WebServlet(name = "UploadServlet", urlPatterns = { "/upload.do" })
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public UploadServlet() {
        super();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");


        String path = this .getServletContext().getRealPath("/" );
         // path is the project root directory: (web project name is test)
         // D:\tomcat\apache-tomcat-8.0.50-windows-x64\ apache-tomcat-8.0.50\webapps\test\ 

        Part part = request.getPart("fileName"); // part represents a file 
String h = part.getHeader("content-disposition" ); // h is to upload The header of the file: as follows (upload the account.txt file on the desktop)      // form-data; name="fileName"; filename="C:\Users\ASUS\Desktop\account.txt"      // Name the uploaded account.txt file as "newFile" and save it in the server      String fname = "newFile" ; // substring is getting the suffix of the file, rename but not changing the suffix fname = fname + h.substring(h .lastIndexOf("."), h.length() - 1 ); // Upload files according to the path (modifying the path can change the storage location of the file in the server) part.write(path + "\\" + fname); // Prompt upload success PrintWriter out = response.getWriter(); out.println("<html><head>"); out.println( "<title>Upload file</title></head>" ); out.println("<body>"); out.println( "<h2>Upload successful!</h2>" ); out.println("</body></html>"); } }

 

Summarize

  I think the most critical statement is  Part part = request.getPart("fileName");  I understand the Part interface as the file itself, part.write(path + "\\" + fname); It is understood as the part in parentheses The path is written in, where the path contains the file name, which is equivalent to a box, and part is the actual file content in the box.

  The method of obtaining the file suffix is ​​worth noting.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324786741&siteId=291194637