Location>code7788 >text

Underlying principles of Java SE file uploads and file downloads

Popularity:200 ℃/2024-07-28 14:13:20

1. Java SE file upload and file download underlying principles

@

catalogs
  • 1. Java SE file upload and file download underlying principles
  • 2. Uploading of documents
    • 2.1 File Upload Application Example
    • 2.2 File Upload Considerations and Details
  • 3. Downloading of documents
    • 3.1 File Download Application Example
    • 3.2 File Download Notes and Details
  • 4. Summary:
  • 5. In conclusion.


2. Uploading of documents

  1. File uploading and downloading are common functions. Note: Here our file upload is only for small files on theupload . If you are transferring large files, you usually use a specialized tool or plug-in.

File upload and download need to use the following two packages, you need to import. Also remember to import and load them into the project.

在这里插入图片描述

在这里插入图片描述

Schematic diagram of the file upload principle:

在这里插入图片描述

在这里插入图片描述

Interpretation of file uploads:

  1. File uploads still use theform (document) Submitted in accordance with
  2. included among theseaction The designation is still in accordance with the previous rules
  3. method Specify post because file uploads are larger files and get cannot send larger files.
  4. enctype:encodetype The encoding type to be set to:multipart/form-data If you want to submit a binary file, multipart/form-data: means that the data submitted by the form is composed of multiple parts, i.e., you can submit binary data and text data, both of which are fine.在这里插入图片描述
  1. Attention:enctype:encodetype The default is:enctype="application/x-www-form-urlencoded" That is, URL encoding, this encoding is not suitable for the submission of binary file data, generally applicable to the submission of text data.

Operate the upload file process:

  1. Determine if it is a file form
  2. Determine what type each form item submitted by the form is
  3. If it's a regular form item, it's treated as text.
  4. If it is a file form entry (binary data), use IO techniques for processing.
  5. Take the file data submitted by the form and save it to a directory on the server side that you specify.

2.1 File Upload Application Example

在这里插入图片描述

Front-end page code for file upload : jsp

在这里插入图片描述

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <base href="<%=()+"/"%>>">
    <style type="text/css">
        input[type="submit"] {
            outline: none;
            border-radius: 5px;
            cursor: pointer;
            background-color: #31B0D5;
            border: none;
            width: 70px;
            height: 35px;
            font-size: 20px;
        }

        img {
            border-radius: 50%;
        }

        form {
            position: relative;
            width: 200px;
            height: 200px;
        }

        input[type="file"] {
            position: absolute;
            left: 0;
            top: 0;
            height: 200px;
            opacity: 0;
            cursor: pointer;
        }
    </style>
    <script type="text/javascript">
        function prev(event) {
//Get the area where the image is displayed
            var img = ("prevView");
//Getting File Objects
            let file = [0];
//Get File Reader
            let reader = new FileReader();
            (file);
             = function () {
//do sth (for sb) img (used form a nominal expression) src Setting up pictures url
                ("src", );
            }
        }
    </script>
</head>
<body>
<!-- 表单(used form a nominal expression) enctype attribute should be set to multipart/form-data -->
<form action="fileUploadServlet" method="post" enctype="multipart/form-data">
    hometown map: <img src="" alt="" width="200" height="200" id="prevView"> <input type="file" name="pic" id=""
                                                                                value="" onchange="prev(this)"/>
    household name: <input type="text" name="name"><br/> <input type="submit" value="upload"/>
</form>
</body>
</html>

Write a servlet for file uploading.

在这里插入图片描述

package ;


import ;
import ;
import ;
import ;
import ;


import ;
import ;
import ;
import ;
import ;import ;import ;import ;import
import ;

import ;import ;import ;import ;import
import ;import ;import ;import ;import
import ;

public class FileUploadServlet extends HttpServlet {

    /* /* /* /* /* /* /* /* /* /* /* /*
    1. determine whether a file upload form
    2. Determine what type of form item is submitted by the form
    3. if it is an ordinary form item, it will be processed in the way of text
    4. if it is a file form item (binary data), the use of IO technology for processing
    5. save the file data submitted by the form to a directory on the server side that you specify
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        //("Called");


        // 1. Determine if it's a file form (enctype="multipart/form-data")
        if ((request)) {
            If ((request)) { //("OK"); // 2.
            // 2. Create a DiskFileItemFactory object to build a tool object that parses the uploaded data.
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); // 2. Create a DiskFileItemFactory object to build a tool object for parsing uploaded data.
            // 3. Create a tool object that parses the uploaded data.
            ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); // Create a tool object that parses the uploaded data.

            // 4. The key point is that the servletFileUpload object parses the data submitted by the form text/file // into a FileItem.
            // into a FileItem file item.
            // Mr. Han's programming lesson: If we don't know what an object is structured to be // we can: 1.
            // You can 1. output the object, and 2. debug it.
            try {
                List<FileItem> list = (request).
                //("List ==>" + list);
                // Iterate through and process ==> separately Natural Idea
                for (FileItem fileItem : list) {
                    // : cannot be cast to
                    //("fileItem == >" + fileItem);
                    if (()) { // if true is text input text
                        String name = ("utf-8"); ("Picture name"); ("Picture name")
                        ("Picture name: " + name); // if (()) { // If true, it is text.

                    } else { // is a file
                        // Get the name of the uploaded file.
                        String name = (); ("Uploaded image name: " + name); } else { // is a file // Get the name of the uploaded file.
                        ("Uploaded filename: " + name);

                        // Save the uploaded file under temp to the directory you specified.
                        // 1. Specify a directory, the working directory of our website.
                        String filePath = "/upload/"; // Save the uploaded file in temp to the directory you specified.

                        // 2. Get the full directory [io/servlet base].
                        String fileRealPath = ().getRealPath(filePath);

                        ("fileRealpath = " + fileRealPath);

                        // 3. Create this uploaded directory = > Create Directory = > Java object
                        // To prevent a large number of directories from being created, you can create multiple directories with more date and time
                        File fileRealPathDirectory = new File(fileRealPath + ()); if (!
                        fileRealPathDirectory = new File(fileRealPath + ()); if (! ()) { // Create if (!
                            (); // create

                        }

                        // Solve the problem of receiving a file name in garbled Chinese
                        ("utf-8"); }
                        // 4. Copy the file to the fileRealPathDirectory directory.
                        // Build a full path to the uploaded file: directory + filename.
                        // Sometimes - "uploads fail", maybe it's a directory problem, add "/".
                        // Texts are overwritten, we also have a utility class to make the filenames not duplicated.
                        // Process the uploaded filename by adding a prefix in front of it to make sure it's unique.
                        name = ().toString() + "_" + () + "_" + name;
                        String fileFullPath = fileRealPathDirectory + "/" + name;
                        (new File(fileFullPath)).

                        // Prompts for information
                        ("text/html;charset=utf-8"); ().
                        ().write("Uploaded successfully");

                    }
                }
            } catch (FileUploadException e) {
                throw new RuntimeException(e); } } catch (Exception e) { {
            } catch (Exception e) {
                throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); }
            }
        } else {
            ("Not a file form...") ;
        }
    }

}

Supplementary explanation of the Servlet for uploading files:

Sometimes - "The upload failed, it may be a directory problem, add "/".

In order to prevent the creation of a large number of directories, you can add a date and time to create multiple directories, so that if you create a directory by date and day, there will be at most 365 directories in a year.

在这里插入图片描述

File fileRealPathDirectory = new File(fileRealPath+ ());
String fileFullPath = fileRealPathDirectory +"/"+ ();

    public static String getYearMonthDay() {
        // How to get the current date-》Javainfrastructural dates,class III
        LocalDateTime localDateTime = ();
        int year = ();
        int monthValue = ();
        int dayOfMonth = ();
        String yearMonthDay = year + "-" + monthValue + "-" + dayOfMonth;

        return yearMonthDay;
    }

The problem of text being overwritten by replacement, we also a tool class so that the file name is not duplicated

// ().toString() hashes non-repeating values
// () Get the current system time when the millisecond level of the
// Process the name of the uploaded file by adding a prefix to make sure it's unique.
// Also split using a specific "_" symbol for the filename that you may need to get later, most convenient to use

name = ().toString() + "_" + () + "_" + name;
String fileFullPath = fileRealPathDirectory + "/" + name;

在这里插入图片描述

Run the test: see if the file can be uploaded successfully

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

2.2 File Upload Considerations and Details

  1. If you upload all the files to one directory, when you upload a lot of files, it will cause the speed of accessing the files to slow down, so you can upload the files to different directories. For example, if you upload the files on one day, put them into one folder Year, Month, and Day, e.g.: 2024-7-1, 21001010 folder.

  2. A perfect file upload, there are many factors to consider, such as breakpoints, control the size of the image, the size of the upload, split up the upload, to prevent malicious uploads, etc., in the project, you can consider using the WebUploader component (Baidu Development)/webuploader/doc/ 在这里插入图片描述

  3. File upload function, in the project is recommended to have limited use, generally used in the avatar, proof, contract, product display, etc., if not limited, it will cause the server space is occupied by a large number of [for example, b-site comments, you can not pass the picture, WeChat sent 1 time the maximum number of 9 pictures of the circle of friends, etc. ...].

  4. File upload, create web/upload folder, in tomcat startup, did not create the corresponding upload folder in the out directory, the reason is that tomcat corresponding to the empty directory will not create the corresponding directory in the out directory, so, just in the upload directory, a file can be put, this is Idea + Tomcat problem, the actual development will not exist. This is an Idea + Tomcat problem, and will not exist in actual development.

3. Downloading of documents

Schematic analysis diagram of file download:

在这里插入图片描述

File Download Response Header Description:

  1. Content-Disposition: Indicates how the downloaded data will be presented, e.g. inline (as a web page or part of a web page) or as a file download attachment
  2. Content-Type: Specifies the type of data to be returned MIME ---- 》http protocol content

File Download Response Body Description:

  1. It's the image's native data when transmitted over the network (encoded as downloaded by the browser)
  2. This image is viewed after downloading, i.e. the browser itself is parsing it.

在这里插入图片描述

3.1 File Download Application Example

Front-end page code for file upload : jsp

在这里插入图片描述

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en"> <head>.
<head>
    <meta charset="UTF-8"> <title>.
    <title> file download</title>
    <base href="<%=()+"/"%>>">" >
</head>
<body>
<h1> file download</h1>
<a href="fileDownLoadServlet?name=">Click to download Java image</a> <br/> <br/>
<a href="fileDownLoadServlet?name=13-Chapter-12-Network-Programming.pptx">Click to download 13-Chapter-12-Network-Programming.pptx</a><br/><br/>
</body>
</html>

Note: we download is, the client from the server to download the content, so we need to simulate the server, on the server to add, our client can download to the content of the file (here: we in the web directory, create a download directory, used to store our client (browser) can be downloaded to the file).

在这里插入图片描述

Note: After you have created the directory and added the files, restart the Tomcat server so that the download directory we added is added to theout Go to the middle of the work catalog.在这里插入图片描述

If you restart the Tomcat server and don't see the download you created in the working directory out, click rebuild project -> restart project

在这里插入图片描述

A small detail: if the directory created in the web directory is an empty folder/ directory, that is, there is nothing in the directory, even if you restart the Tomcat server will not be added to the out directory. So, just put a file in the upload directory, this is an Idea + Tomcat problem, the actual development will not exist!

Write a servlet for downloading files.

在这里插入图片描述

package ;

import ;
import .BASE64Encoder ;import ;import .BASE64Encoder ;import .

BASE64Encoder; import ;
BASE64Encoder; import ;
BASE64Encoder; import ;
import ;
import ;import ;import ;import ;import
import ;import ;import ;import ;import
import ;import ;import ;import ;import
import ;import ;import ;import ;import
import ;

public class FileDownLoadServlet extends HttpServlet {
    public class FileDownLoadServlet extendsss HttpServlet { @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        ("Called");

        // 1. Prepare the files to be downloaded (assuming they are public resources).
        // IMPORTANT: Make sure that when our tomcat is started, there is a download folder out in the working directory and that
        // have a download folder in the working directory when tomcat is started, and // have the files available for download!
        // Again, if you don't see the download you created in the working directory out rebuild project -> restart proj

        // 2. Get the name of the file you want to download.
        ("utf-8"); String downLoadFile
        String downLoadFileName = ("name"); ("downLoadFileName"); ("utf-8"); ("utf-8")
        ("downLoadFileName = " + downLoadFileName);

        // 3. Give the http response, set the response header Content-Type, which is the MIME of the file.
        // Get it from the servletContext
        ServletContext servletContext = (); String downLoadPath = (); String downLoadPath = ()
        String downLoadPath = "/download/"; // Server resource image, storage path.
        
        String mimeType = (downLoadFileFullPath); ("mimeType = downLoadFileName"); // Path to the server resource image.
        ("mimeType = " + mimeType);
        (mimeType);

        // 4. Setting the response header Content-Dispostion for the http response.
        // There are a lot of details to consider here, such as how different browsers write it, and encoding.
        // ff is base64 for Chinese filenames, and ie/chrome is URL-encoded.
        // We don't need to learn the Simon mechanism here, we just need to know how it works.
        if((("User-Agent").contains("Firefox")) {
            // Firefox's settings are Base64 encoded
            ("Content-Disposition", "attachment; filename==?UTF-8?B?" + new BASE64Encoder)
                    new BASE64Encoder().encode((("UTF-8"))); } else { new BASE64Encoder().encode(("UTF-8")))
        } else {
            // Others (mainstream ie/chrome) use URL encoding operations
            ("Content-Disposition", "attachment; filename=" +
                    (downLoadFileName, "UTF-8")); }
        }

        // 5. Read the following file data and return it to the client
        // (1) Create an input stream associated with the file to be downloaded.
        InputStream resourceAsStream = (downLoadFileFullPath);

        // (2) Get the output stream for the returned data {since most of the returned file is binary (bytes), IO Java Basics}
        ServletOutputStream outputStream = ();

        // (3) Use a utility class to copy the file associated with the input stream to the output stream and return it to the client/browser.
        // Note that the import ; package has the
        (resourceAsStream,outputStream);

    }
}

Supplementary explanation of Servlets for upload and download operations:

File download, the more troublesome is the different browser file name Chinese processing, therefore, in the code, you need to do for different browsers to deal with. Here: firefox is the file name Chinese need base64 encoding, and ie/chrome is URL encoding. For different browsers, we need to do different encoding processing.

在这里插入图片描述

// 4. Give http response, set response header Content-Dispostion
        // There are a lot of details to consider here, such as how different browsers write it, and encoding.
        // ff is base64 for filenames, and ie/chrome is URL encoding.
        // We don't need to learn the Simon mechanism here, we just need to know how it works.
        if((("User-Agent").contains("Firefox")) {
            // Firefox's settings are Base64 encoded
            ("Content-Disposition", "attachment; filename==?UTF-8?B?" + new BASE64Encoder)
                    new BASE64Encoder().encode((("UTF-8"))); } else { new BASE64Encoder().encode(("UTF-8")))
        } else {
            // Others (mainstream ie/chrome) use URL encoding operations
            ("Content-Disposition", "attachment; filename=" +
                    (downLoadFileName, "UTF-8")); }
        }

Run the test:

在这里插入图片描述

在这里插入图片描述

3.2 File Download Notes and Details

  1. file download, the more troublesome is different browser file name Chinese processing, therefore, in the code, you need to do for different browsers to deal with.在这里插入图片描述

  2. For website files, many files can be downloaded by using Save As, for large files (documents, videos), professional download tools (Xunlei, Baidu, Tencent, Huawei NetDisk, etc.) will be used.

  3. For different browsers, after the file has been downloaded, it will be handled differently, some will open the file directly, some will download the file to the local/download directory.

4. Summary:

  1. Handling of attributes on the form for file uploads:method Specify post because file uploads are larger files and get cannot send larger files.enctype:encodetype The encoding type to be set to:multipart/form-data If you want to submit a binary file, multipart/form-data: means that the data submitted by the form is composed of multiple parts, i.e., you can submit binary data and text data, both of which are fine.

  2. Sometimes - "The upload failed, it may be a directory problem, add "/".

  3. In order to prevent the creation of a large number of directories, you can add a date and time to create multiple directories, so that if you create a directory by date and day, there will be at most 365 directories in a year.

  4. The problem of text being overwritten by replacement, we also a tool class so that the file name is not duplicated

    // ().toString() hashes non-repeating values
    // () Get the current system time when the millisecond level of the
    // Process the name of the uploaded file by adding a prefix to make sure it's unique.
    // Also split using a specific "_" symbol for the filename that you may need to get later, most convenient to use

    name = ().toString() + "_" + () + "_" + name;
    String fileFullPath = fileRealPathDirectory + "/" + name;
    
    
  5. File upload function, in the project is recommended to have limited use, generally used in the avatar, proof, contract, product display, etc., if not limited, it will cause the server space is occupied by a large number of [for example, b-site comments, you can not pass the picture, WeChat sent 1 time the maximum number of 9 pictures of the circle of friends, etc. ...].

  6. File download: A small detail: If the directory created in the web directory is an empty folder / empty directory, that is, there is nothing in the directory, even if you restart the Tomcat server will not be added to the out directory. So, you just need to put a file in the upload directory, this is an Idea + Tomcat problem, the actual development will not exist.

  7. File download, the more troublesome is the different browser file name Chinese processing, therefore, in the code, you need to do for different browsers to deal with. Here: firefox is the file name Chinese need base64 encoding, and ie/chrome is URL encoding. For different browsers, we need to do different encoding processing.

在这里插入图片描述

  1. About file upload and download, here is the use of native API way, in the actual development, we have these file upload and download, are encapsulated by the framework, such as : Spring MVC, Spring Boot, etc., we only need to call the corresponding API can be, the framework encapsulation is too good, it is difficult for us to understand the underlying principles. Here the file upload and download is the underlying principle.

5. In conclusion.

Limited to their own level, which exists in the error, I hope you give guidance, Han Xin point troops - more good, thank you, we will see you again, see you in the river and lake!

在这里插入图片描述