After cutting the mountain, I met suddenly

After cutting the mountain, I met suddenly

The only things I can remember this week are program rehearsals, competition training and catching up with projects.
However, among these things, the only thing that makes me feel is to catch up with the project. I still remember that I only logged in and registered when I was last assessed. Other things are still very vague. It seems that it is impossible to finish this project.
As of yesterday, all the other modules had been completed except for two modules. I believe it will be different after a period of time
The most difficult part of the project is the video upload. Because it was done with others, the whole idea was owned by others, and there was no video upload in it. It was very difficult for me to do video upload. In order to understand this, I asked the senior four times, at least half an hour each time, and once for more than an hour. At that time, I felt that I was really hot. Even slightly humble. And in order to upload the video, it took two whole days at a time, which was very uncomfortable. But now it seems that it's just that thing, that little thing. Maybe it's because I overcome it that I suddenly realized it.
Now think about it carefully, let me understand that it is right that everything is difficult at the beginning. Some things that seem insurmountable will know the result only when they are done. If you don't do it, it will always be difficult for yourself.

Upload file method

Create a file upload form
The following points need attention:
The method property of the form should be set to the POST method instead of the GET method.
The form enctype attribute should be set to multipart / form data
The action attribute of the form should be set to process the Servlet file uploaded by the file on the back-end server. The following example uses uploadservlet to upload files.
To upload a single file, you should use a single < input... / > tag with the attribute type = "file". To allow multiple files to be uploaded, please include multiple input tags with different name attribute values. Enter the value of the attribute with a different name for the label. The browser associates a browse button with each input tag.

<%@ 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 instance - Rookie tutorial</title>
</head>
<body>
<h1>File upload instance - Rookie tutorial</h1>
<form method="post" action="/TomcatTest/UploadServlet" enctype="multipart/form-data">
    Select a file:
    <input type="file" name="uploadFile" />
    <br/><br/>
    <input type="submit" value="upload" />
</form>
</body>
</html>

Write background Servlet

The following is the source code of UploadServlet, which is the same as processing file upload. Before that, make sure that the dependent package has been introduced into the WEB-INF/lib directory of the project:

The following example depends on FileUpload, so make sure that you have the latest version of Commons - FileUpload in your classpath x. X.jar file. Can from http://commons.apache.org/proper/commons-fileupload/ Download.
FileUpload depends on Commons IO, so be sure to have the latest version of commons-io-x.x.jar file in your classpath. Can from http://commons.apache.org/proper/commons-io/ Download.
You can directly download the two dependency packages provided by this site:

commons-fileupload-1.3.2.jar
commons-io-2.5.jar

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
 

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
     
    // Upload file storage directory
    private static final String UPLOAD_DIRECTORY = "upload";
 
    // Upload configuration
    private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB
 
    /**
     * Upload data and save files
     */
    protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
        // Detect whether it is multimedia upload
        if (!ServletFileUpload.isMultipartContent(request)) {
            // If not, stop
            PrintWriter writer = response.getWriter();
            writer.println("Error: The form must contain enctype=multipart/form-data");
            writer.flush();
            return;
        }
 
        // Configure upload parameters
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // Set the memory threshold - when exceeded, a temporary file will be generated and stored in the temporary directory
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // Set temporary storage directory
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
 
        ServletFileUpload upload = new ServletFileUpload(factory);
         
        // Set maximum file upload value
        upload.setFileSizeMax(MAX_FILE_SIZE);
         
        // Set the maximum request value (including file and form data)
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // Chinese processing
        upload.setHeaderEncoding("UTF-8"); 

        // Construct a temporary path to store uploaded files
        // This path is relative to the directory of the current application
        String uploadPath = request.getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY;
       
         
        // Create if directory does not exist
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
 
        try {
            // Parse the requested content and extract the file data
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);
 
            if (formItems != null && formItems.size() > 0) {
                // Overlap represents single data
                for (FileItem item : formItems) {
                    // Process fields that are not in the form
                    if (!item.isFormField()) {
                        String fileName = new File(item.getName()).getName();
                        String filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);
                        // Upload path of output file on console
                        System.out.println(filePath);
                        // Save file to hard disk
                        item.write(storeFile);
                        request.setAttribute("message",
                            "File uploaded successfully!");
                    }
                }
            }
        } catch (Exception ex) {
            request.setAttribute("message",
                    "error message: " + ex.getMessage());
        }
        // Jump to message jsp
        request.getServletContext().getRequestDispatcher("/message.jsp").forward(
                request, response);
    }
}

Added by pthes on Tue, 08 Mar 2022 19:45:55 +0200