1. Upload files

1.1 File Uploading Example

1.1.1 Analysis File Upload page

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<! DOCTYPEhtml 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>Insert title here</title>
</head>
<body>
	<h1>Long file transfer</h1>
	<! --enctype=" open multimedia TAB "-->
	<form action="http://localhost:8091/file" method="post" 
	enctype="multipart/form-data">
		<input name="fileImage" type="file" />
		<input type="submit" value="Submit"/>
	</form>
</body>
</html>
Copy the code

1.1.2 Edit the File upload page

package com.jt.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@RestController // Indicates that the returned data is a JSON
public class FileController {

    / * * * business description: implement user file upload * url: http://localhost:8091/file * request parameters: fileImage * return values: successful operation string * file upload capacity: 1 m * / default conditions
    @RequestMapping("/file")
    //MultipartFile Interface created by SpringBoot
    public String file(MultipartFile fileImage) throws IOException {
        String dir = "D:/JT-SOFT/images";
        File dirFile = new File(dir);
        if(! dirFile.exists()){ dirFile.mkdirs();// Creates multi-level directories
        }
        // Get the name of the file
        String fileName = fileImage.getOriginalFilename();
        // Encapsulate the file into a complete path
        File imageFile = new File(dir+"/"+fileName);
        // The outputStream interface provides a method to upload files.
        fileImage.transferTo(imageFile);
        return "File uploaded successfully!!"; }}Copy the code

Bold style ## 1.2 file upload implementation

1.2.1 Page Parameter Analysis

1). Request url

2). Request parameters:

var TT = KindEditorUtil = {		// Equivalent to the utility classes defined in Java, which provide many static methods.
	// Editor parameters
	kingEditorParams : {
		filePostName  : "uploadFile".// The specific parameter name of the request
		uploadJson : '/pic/upload'.// The requested path information
		dir : "image"
	},
Copy the code

3). Return the result request

  • Attribute 1: error=0 File upload success 1. File upload failure n
  • Property 2: URL address: the virtual path after the image is uploaded
  • Property 3: Width /height is an image-specific property
 {"error":0."url":"Save path of picture"."width": The width of the picture,"height"The height of the image}Copy the code

1.2.2 encapsulation ImageVO

package com.jt.vo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.io.Serializable;

@Data
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
public class ImageVO implements Serializable {
    / / {" error ": 0," url ":" the save the path of the picture ", "width" : the width of the image, "height" : the height of the image}
    private Integer error;      //0 is normal. 1 is incorrect
    private String url;         // Image virtual path
    private Integer width;      / / width
    private Integer height;     / / height

	/ / fail
    public static ImageVO fail(a){

        return new ImageVO(1.null.null.null);
    }
	/ / success
    public static ImageVO success(String url,Integer width,Integer height){

        return new ImageVO(0, url,width,height); }}Copy the code

1.2.3 About regular expressions

Regular expressions are also called regular expressions. Regular Expression (often abbreviated as regex, regexp, or RE in code) is a computer science concept. Regular expressions are often used to retrieve and replace text that conforms to a pattern (rule).

1.2.4 编辑FIleController

 / * * * business implementation: file upload implementation * URL: http://localhost:8091/pic/upload? Dir =image * Parameter: uploadFile * Returned value: ImageVO */
    @RequestMapping("/pic/upload")
    public ImageVO uploadFile(MultipartFile uploadFile){

        return fileService.uploadFile(uploadFile);
       / * String url = "https://img14.360buyimg.com/n0/jfs/t1/151857/40/2398/38943/5f8842b9Edac7df98/0a8a77bfea24aa1d.jpg"; return ImageVO.success(url, 800, 800); * /
    }
Copy the code

1.2.5 Editing the Properties configuration file

Note: Because the file upload path and URL address may change, if written to the code is not easy to maintain. So it’s best to write the information to the configuration file.

image.localDirPath=E:\jt\JT-SOFT\images
image.urlPath=http://image.jt.com
Copy the code

1.2.6 editor FileServiceImpl

Edit FileService, where attribute values are dynamically injected.

package com.jt.service;

import com.jt.vo.ImageVO;
import com.sun.xml.internal.bind.v2.model.core.TypeInfoSet;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

@Service
@PropertySource("classpath:/properties/image.properties")
public class FileServiceImpl implements FileService{

    @Value("${image.localDirPath}")
    private String localDirPath;    // = "D:/JT-SOFT/images";
    @Value("${image.urlPath}")
    private String urlPath;         // = "http://image.jt.com";


   /* private static Set
      
        typeSet = new HashSet<>(); Static {typeset.add (" JPG "); typeSet.add("png"); typeSet.add("gif"); } * /
      

    /** * File upload policy: * 1. Image type verification 1. Regular expression.. 2.????? Exe. JPG Width/height * 3. Storing files in directories 1. Hash ASdfsdfa 2. Time * 4. Prevent file name uUID as name *@param uploadFile
     * @return* /
    @Override
    public ImageVO uploadFile(MultipartFile uploadFile) {
        //1. Image type verification
        //1.1 Obtain the image name abc.jpg
        String fileName = uploadFile.getOriginalFilename();
        // To solve the case problem of the operating system, all characters need to be lowercase
        fileName = fileName.toLowerCase();
        / / 1.2 interception JPG | PNG | GIF images type
        //^ row first /$row bits /* Number of matches /+ at least once /? Yes or no
        //{n,m} matches at least n times and at most M times / [xyz] character set /() group / \\ escape character
        if(! fileName.matches("^.+\\.(jpg|png|gif)$")) {return ImageVO.fail();
        }

        //2. Check whether the program is malicious
        try {
            // Read the file information through the IO stream and convert it to the image type
            BufferedImage bufferedImage = ImageIO.read(uploadFile.getInputStream());
            int height = bufferedImage.getHeight();
            int width = bufferedImage.getWidth();
            if(height == 0 || width == 0) {// This file is a malicious program
                return ImageVO.fail();
            }

            //3. Dynamically generate file directories based on time
            String dateDirPath =
                    new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());

            D:/ jt-soft /images/2021/03/15/
            String localDir = localDirPath + dateDirPath;
            //3.2 Dynamically generating file path
            File dirFile = new File(localDir);
            if(! dirFile.exists()){// Generate directories dynamically
                dirFile.mkdirs();  // Create multi-level directories
            }

            //4. Dynamically generate the user name uuid.jpg to prevent the same name
            String uuid = UUID.randomUUID().toString().replace("-"."");
            int index = fileName.lastIndexOf(".");// Start from the end
            String fileType = fileName.substring(index);
            String realFileName = uuid + fileType;// The actual file name

            //5. Upload files. File directory localDir/File name realFileName
            File imageFile = new File(localDir + realFileName);
            uploadFile.transferTo(imageFile);// Upload the file

            //6. Join virtual paths
            // http: //image.jt.com/2021/03/09/uuid.jpg
            // E:\JT-SOFT\images\ 2021\03\09\uuid.jpg
            String url = urlPath + dateDirPath + realFileName;
            return ImageVO.success(url, width, height);
            
        } catch (IOException e) {
            e.printStackTrace();
            returnImageVO.fail(); }}}Copy the code

2. Agency mechanism

2.1 Picture agent description

2.2 Reverse proxy mechanism

2.2.1 Reverse Proxy description

The reverse proxy server is located between the user and the target server, but for the user, the reverse proxy server is equivalent to the target server, that is, the user can directly access the reverse proxy server to obtain the resources of the target server. At the same time, the user does not need to know the address of the target server, and does not need to make any Settings on the client. A reverse proxy server is usually used as a Web accelerator, that is, the reverse proxy is used as the front machine of the Web server to reduce the load on the network and server and improve the access efficiency.

2.2.2 Features of reverse Proxy

The reverse proxy is a server-side proxy (protects data on the back-end server).

2.2.3 Application of reverse proxy

Users don’t know who the real server is.

2.2 Forward proxy mechanism

2.2.1 Forward Proxy

Is a server that sits between the client and the origin server. To get content from the original server, the client sends a request to the proxy and specifies the target (the original server), and the proxy passes the request to the original server and returns the obtained content to the client. The forward proxy can only be used by clients.

2.2.2 Features of forward Proxy

1. The user sends a request to the proxy and specifies the target server (the user knows who the server is) 2. The forward proxy is a client proxy that protects user information. 3. The forward proxy is used to implement network communication.

2.3 Nginx

2.3.1 Nginx is introduced

Nginx (Engine X) is a high-performance HTTP and reverse proxy Web server that also provides IMAP/POP3/SMTP services. Nginx was developed by Igor Sessoyev for the second most visited Rambler.ru site in Russia (RU: р а блер). The first public version 0.1.0 was published on 4 October 2004. It distributes source code under a BSD-like license and is known for its stability, rich feature set, sample configuration files, and low system resource consumption. On June 1, 2011, Nginx 1.0.4 was released. Nginx is a lightweight Web server/reverse proxy server and email (IMAP/POP3) proxy server, distributed under the BSD-like protocol. Nginx is characterized by small memory and strong concurrency capability. In fact, nginx performs better in concurrency capability among web servers of the same type. Users of NGINx website in mainland China include baidu, JD, Sina, netease, Tencent, Taobao, etc.

Feature 1: The memory usage is less than 2 MB. Feature 2: The concurrency capability is 50000 / s. 20-30000 / s

2.3.2 Downloading/Installing Nginx

Website:Nginx.org/en/download…

2.3.3 Description of process items

Main process: the process that provides the reverse proxy service. Daemons: Prevent accidental shutdown of the main process

2.3.4 nginx-related commands

Note: The administrator only needs to start Nginx once. The Nginx startup will occupy port 80. If the Nginx startup fails, check the problem set. Command execution location: The command must be executed in the nginx root directory

  • 1. Start nginx: start nginx
  • 2. Nginx restarts: nginx -s reload -s: indicates the task tree
  • 3. Nginx stop: nginx -s stop

2.4 Getting Started with reverse Proxy

Core profile:

  • Nginx configuration must be done within the HTTP protocol. Otherwise it does not work!
  • Each server is a reverse proxy service
Server {# listening port = "server"80Ports rarely change LISTEN80; # Intercept user request for domain name server_name localhost; # configure reverse proxy/to intercept all requests on behalf of location / {The #root keyword represents a directory
            root   html;
            The #index keyword accesses the page by defaultindex index.html index.htm; }}Copy the code

2.5 Product Picture Output

2.5.1 Editing the nginx.conf configuration file

After the modification, restart nginx

# Image server configuration server {listen80; server_name image.jt.com; Root E:/ jt-soft /images; }Copy the code

2.5.2 Picture Output Flowchart

2.5.3 Editing the HOSTS file

0).HOSTS file is used to realize the mapping between domain names and IP addresses on the local computer.

1) path2). Edit content

#@SwitchHosts! {"url": null."icon_idx": 0."title": "\u5f53\u524d\u7cfb\u7edf hosts"} #192.168126.129.  image.jt.com
#192.168126.129.Manage.jt.com #IP domain mapping127.0. 01.  image.jt.com
127.0. 01.  manage.jt.com
127.0. 01.  www.jt.com
127.0. 01.  sso.jt.com
127.0. 01.Localhost #bug drop last letter problemCopy the code

2.5.4 About switchHosts

Software to be used: switchHosts You can contact the author or baidu switchHosts to obtain the software download link


1). About the file directory

2). Run as an administrator

Jingtao configuration #192.168126.129.  image.jt.com

#192.168126.129.Manage.jt.com #IP domain mapping127.0. 01.  image.jt.com

127.0. 01.  manage.jt.com

127.0. 01.  www.jt.com

127.0. 01.  sso.jt.com

127.0. 01.Localhost #bug drop last letter problemCopy the code

2.5.5 Page effect