当前位置:网站首页>[actual combat - dry goods] take you to build your own FTP server to upload and download files

[actual combat - dry goods] take you to build your own FTP server to upload and download files

2021-10-14 06:39:44 It learning diary



  • Personal home page : IT Study diary
  • 🤟 Copyright : This paper is written by 【IT Study diary 】 original 、 stay CSDN First episode 、 If you need to reprint, please contact the blogger
  • If it helps you 、 Welcome to your attention 、 give the thumbs-up 、 Collection ( One key, three links ) And subscribe to columns .
  • Want to get into 【 Technical circles 】、 Please check the left navigation bar ! through 、 Pass by 、 Don't miss !

One 、 Preface

️ One 、 Preface


  • Hello everyone , I'm Xiao Cheng , Before you start to learn , First of all, I'd like to recommend the recently planned 【 Technical circles 】, There is no more civilized 20 For days , I've been combing the previous articles, knowledge and learning resources , Now it has been preliminarily sorted out , All resources in the circle are shared for free , Resources include but are not limited to interview resources 、 The resume template 、 Year end report PPT、CSDN VIP Download resources, etc , If you are interested, please click 【 Technical circles 】, Looking forward to your joining .

  • If it helps you , You can help with one click three links and column subscription !

  • This article focuses on :Window Environment building FTP The server ,JAVA Program realization FTP Server file upload 、 Download function .


Two 、 Column recommendation

️ Two 、 Column recommendation


   Recommendation of conscience : The following related technical columns are still being shared for free , We can help you subscribe !

   Interview dry goods column

   Common development questions column

  JAVA Advanced knowledge column

   from 0 To 1- Comprehensive and profound understanding MySQL Series column


3、 ... and 、Window System Ftp Server setup

3、 ... and 、Window System FTP Server setup


   In the building FTP Before server , Let me introduce to you what is FTP The server , Otherwise, I'm afraid some friends may just have a vague concept , Learn as much as you can , Know why , Don't know a little , Otherwise, it's not practical to use it by yourself .

3.1、FTP How does the server play


   Before the introduction , Let's take a look at it first FTP How can I play after the server , Otherwise, some friends always feel that the article is too long and run away halfway , If you miss it, there will be no more !

  1、 Upload 、 Download a small video ( Shared files ), Custom permission control , Control the use of users .

  2、 Realize file storage and file download in some business scenarios ( File server operation ).

  3、 More playing methods are waiting for you to develop , Play your brain hole …


3.2、FTP(File Transfer Protocol, File transfer protocol )


   Let's get to know FTP agreement ,FTP The abbreviation of file transfer protocol , It is TCP/IP A member of a protocol family , It's also Internet One of the first protocols used on , It can realize various operations of files between computers ( Such as the addition of documents 、 Delete 、 Change 、 check 、 Transmission, etc ),FTP The goal is to improve file sharing , Provides indirect use of remote computers , Realize the mutual operation of computer files , Make the storage medium transparent to users and transfer data reliably and efficiently .

   It is based on C/S( client / Server side ) Model design , The application layer working in the network architecture , Use TCP transmitted , Ensure that the connection between the client and the server is reliable .

   Supported connection methods :

  FTP Support Standard (PORT The way , Active way ),Passive (PASV, Passive way ) Two connection modes , The connection process is roughly as follows :

  1、FTP Client initiated FTP conversation , And FTP The server establishes the corresponding connection , During the conversation ,FTP Two connections will be established between the control information process and the data process .

  2、 Control the purpose of the process connection : For transmission FTP Control information such as internal command and command response , Unable to transfer data .

  3、 Purpose of data process connection : Used for data transmission between client and server , It's full duplex , It can support two-way data transmission , When the data transmission is completed , It will undo and go back to FTP Conversation state , Until the control connection process is cancelled , Quit the whole FTP conversation .

  PORT Pattern :

  FTP The client will communicate with the server TCP 21 Port create connection ( Control connection ), Used to send commands , When the client needs to receive data , It will send... To the server through this connection PORT name ,PORT The command contains what port will be used to receive the data transmitted by the server , here , The server will pass TCP 20 Port and FTP The client creates a connection ( Data connection ) Complete the data transfer .

  Passive Pattern :

  FTP The client will communicate with the server TCP 21 Port create connection ( Control connection ), Used to send commands , When the client needs to receive data , It will send... To the server through this connection Pasv name , Server received Pasv After the command , Open a temporary port ( The port number is greater than 1023 Less than 65535) And notify the client of the request to transmit data on this port , Client connection FTP Server this port , then FTP The server will transmit data through this port .

   explain : above FTP For the introduction of protocol knowledge, refer to Baidu Encyclopedia :FTP agreement


3.3、FTP The server


   I understand FTP agreement , that FTP The server is easy to understand .FTP Server is support FTP Protocol server , We can usually install one on the computer FTP Tools can be implemented with FTP The server transfers files ,FTP Servers are commonly divided into :Windows FTP The server and Linux FTP The server .

   Our own computer can also be used as a FTP The server , Such as Windows The system can use its own ISS Manager to build a FTP The server ( This case uses this ),Linux The most commonly used method of the system is vsftp Software do FTP Server setup .

   Common examples : When taking computer classes or computer exams at school , The teacher will put the class questions or examination questions in a folder , Ask students to visit an address, such as :ftp://ip Address , Through this address, each student can see the files shared by the teacher , Download the corresponding test questions to complete the exam .

   In the above example, students who have taken computer classes should have experienced ( What a wonderful student time ), What the students visit is actually what the teacher has built FTP The server , The teacher uploads the shared files to FTP The server , Students can download and other operations .

   A lot of wordiness , Let's start FTP Server construction and upload and download function development !


3.4、FTP Server setup


   Installation environment : Win10

   Step one : install FTP Server support and IIS Management platform .

   Operation steps : The computer => Control panel => Procedures and functions => Turn on and off Windows function => Internet Infomation Services => Check 【FTP The server 】 and Web Management tools 【IIS Administrative console 】=> Click OK to wait for the installation to complete


 install Windows Of FTP Components

   Step two : open IIS Manager

   Operation steps : The computer => Control panel => Management tools => Internet Infomation Services(IIS) Manager


IIS Management platform

   Step three : establish FTP The server

   operation 1: In a drive letter such as D disc , Create a FTP Shared folders , be used for FTP Shared file storage address

   step 2: Right click IIS The left navigation bar of the manager => add to FTP Site


 Insert picture description here

   step 3: Appoint 【 Site name 】 and 【FTP Shared folder path 】

 Insert picture description here


   step 4: To configure FTP Server related information


 Insert picture description here

   step 5: To configure FTP Server authentication and permission information 【 Be careful : If you want to upload through the program 、 Download function , The basic options in authentication need to be checked , The following program needs to log in to... With an account and password in this way FTP The server

 Insert picture description here


   step 5: To this step , One FTP The server has been built , stay IIS The manager can also be used for built FTP Server configuration management .

 Insert picture description here

   step 6: Small partners in the same network segment can use :ftp://ftp Configured ip Address Format access to FTP The server .

 Insert picture description here

3.5、FTP Problems with server setup


   Question 1 : FTP After the construction is completed according to the process , Small partners in the same network segment cannot access !

   reason : It may be that firewall interception is turned on , It needs to be released at the firewall FTP The server .

   solve : The computer => Control panel => Windows Defender A firewall => Allow applications to pass through Windows Defender The firewall communicates => Check 【FTP The server 】


 Insert picture description here


Four 、 By program FTP File upload and download

Four 、 By program FTP File upload and download


   Go through the above steps , We finished FTP Server building , You can manually upload files to the server , Let small partners in the same network segment download freely from the above , however , In actual business development , What we need is to upload and download through the program , Instead of manually , below , Let's see how to achieve it .

   explain : The article only Posts part of the code , All case codes have been uploaded to Gitee, Those who need it can directly visit and download ( It helps. Remember to give star ah ):【 actual combat -FTP Server setup , Upload 、 download


4.1、 Project structure


 Insert picture description here

4.2、 implementation technique


  1、Apache Under the commons-net Dependency package : It contains a set of network utilities and protocol implementations , Supported protocols include :FTP、NNTP、NTP、POP3(S)、SMTP(S)、Telnet、Whois wait , You can use it to upload and download files .

  2、spring-boot-starter-web: web Related support

  3、SpringBoot rely on : Fast build JAVA project

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.6</version>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

4.2、 Related configuration


ftp:
  client:
    # ftp The character set used by the client file 
    charset: GBK
  server:
    # ftp Server binding ip Or domain name 
    hostname: 127.0.0.1
    #  port 
    port: 21
    #  Connect ftp User name of the server 
    username: user
    #  password 
    password: 123456
    # ftp Shared file path 
    workingPath: D:/share/FTPServer
    # ftp The character set used by the server file ( It is used to upload files with Chinese names and download files with Chinese names  -  Very important )
    charset: ISO-8859-1


4.3、 Core code


   because FTP Server upload 、 Downloading is a very common function , So bloggers are encapsulated into a tool class , Small partners in need can introduce dependencies and related configurations , You can use this tool class directly .

  1、 Upload core code :

/** *  Upload  * * @return */
    public boolean upload(FtpUploadParam param) {
    
        boolean flag = false;
        FTPClient ftpClient = new FTPClient();
        //1  Test connection 
        if (connect(ftpClient, param.getHostname(), param.getPort(), param.getUsername(), param.getPassword())) {
    
            try {
    
                //2  Check if the working directory exists , Create if it does not exist 
                if (!ftpClient.changeWorkingDirectory(param.getWorkingPath())) {
    
                    ftpClient.makeDirectory(param.getWorkingPath());
                }
                //  Encode files into Ftp The server supports encoding types (FTP In the agreement , Specify the file name code as iso-8859-1, Therefore, the directory name or file name needs to be transcoded .)
                String fileName = new String(param.getSaveName().getBytes(ftpClientCharset), ftpServerCharset);
                // 3  Upload files 
                if (ftpClient.storeFile(fileName, param.getInputStream())) {
    
                    flag = true;
                } else {
    
                    log.warn("FtpUtils uploadFile unsuccessfully!!");
                }
            } catch (IOException e) {
    
                log.error("FtpUtils upload in error:{}", e);
            } finally {
    
                disconnect(ftpClient);
            }
        }
        return flag;
    }

  2、 Download the core code :

public boolean download(FtpDownloadParam param, String downloadFileName) {
    
        FTPClient ftpClient = new FTPClient();
        FileOutputStream out = null;
        //1  Test connection 
        if (connect(ftpClient, param.getHostname(), param.getPort(), param.getUsername(), param.getPassword())) {
    
            try {
    
                File file;
                String localPath = param.getDownloadPath() + param.getFileName();
                out = new FileOutputStream(new File(localPath));
                //2  Check if the working directory exists , There is no return 
// if (!ftpClient.changeWorkingDirectory(param.getWorkingPath())) {
    
// return false;
// }
                /* *  open FTP Server's PASS Pattern ( I don't remember FTP For the modes supported by the protocol, please turn to the first stage of the article ) *  This method means before each data connection ,ftp client tell ftp server Open a port to transmit data .  because ftp * server It is possible to open different ports each time to transmit data , But in linux On , Because of security restrictions , Maybe some ports are not open , There may be a blockage  */
                ftpClient.enterLocalPassiveMode();
                //  Set the file transfer method 
                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                //  Encode files into Ftp The server supports encoding types (FTP In the agreement , Specify the file name code as iso-8859-1, Therefore, the directory name or file name needs to be transcoded .)
                //  Lack of encoding conversion will result in : from FTP The file downloaded from the server is damaged , Cannot be opened 
                boolean b = ftpClient.retrieveFile(new String(downloadFileName
                        .getBytes(clientCharset), serverCharset), out);
                out.flush();
            } catch (IOException e) {
    
                log.error("FtpUtils upload in error:{}", e);
                return false;
            } finally {
    
                try{
    
                    if(Objects.nonNull(out)){
    
                        out.close();
                    }
                }catch (Exception e){
    
                    log.error("FtpUtils upload in error:{}", e);
                }
                disconnect(ftpClient);
            }
        }
        return true;
    }

4.4、 Execution results


  1、 Demo code :

 Demo code


  2、 Upload files to FTP The server :

 Upload files to FTP The server

  3、 from FTP The server downloads the file to the local :

 from FTP The server downloads the file to the local


4.5、 Problems encountered in the development process


   problem 1、 Connect FTP Server failed :

   Problem description : The account and password are specified in the configuration file , But the connection failed .

   Solution After investigation , It was found that he was building FTP Only anonymous authentication is enabled on the server , Basic validation is not turned on ( How to log in with account and password ), Just go to IIS Open... In manager 【 Basic verification 】 that will do .

   Solution steps : The computer => Control panel => Management tools => IIS Manager => Set up FTP The server => FTP Authentication => Turn on basic authentication mode .


 Insert picture description here

   problem 2、FTP Failed to upload Chinese file :

   Problem description : Select the file named English to upload normally , However, selecting a Chinese file name failed to upload , error message :550-The filename, directory name, or volume label syntax is incorrect. .

   Solution After investigation , Find out FTP In the agreement , Specify the file name code as iso-8859-1( Be careful : This is now in Windows Built FTP What happens to the server , If it is Linux Environment , You also need to see linux The default support code depends on , But you need to encode the uploaded file name. This step is OK ), Therefore, the directory name or file name needs to be transcoded . So in the upload file code, you will see the following code to decode and re encode the file :

 Insert picture description here

   problem 3、 call FTPClient Method of switching directories changeWorkingDirectory Always fail

   Causes and Solutions : FTP When building the server, we need to make a shared file path , When we talk to FTP After the server establishes the connection , The default is in this directory , If you want to switch to a subdirectory under this directory , You don't need to write a full path .

   Example : If FTP The folder path shared by the server is :D:/ftpserver, At this point, we need to switch to ftpserver Sub files under folder demo in , Correct writing :fTPClient.changeWorkingDirectory("demo") instead of fTPClient.changeWorkingDirectory(“D:/ftpserver/demo”)

 Insert picture description here

   problem 4、 from FTP The file downloaded by the server is damaged , Unable to open

   Problem description : Try from FTP The server downloads a file with a Chinese character file name , After successfully downloaded to the local, it cannot be opened normally , It indicates that it has been damaged .

   Question why : The reason is actually the same as the second question , This is because the file name containing Chinese characters needs to be encoded and converted when downloading , Otherwise, it cannot be opened after downloading .

 Insert picture description here

5、 ... and 、 At the end

6、 ... and 、 At the end


  FTP All codes of the actual combat project of the server have been uploaded to Gitee, You can take it yourself if you need it ( It will be transmitted to CSDN As a free download ), If it helps, don't forget star Oh ,Gitee The through train of the project is as follows :【 actual combat -FTP Server setup , Upload 、 download

   Recommend it : 【 Technical circles 】 There are free interview resources in 、 The resume template 、 Year end report PPT、CSDN VIP Download resources, etc , Looking forward to your joining !【 Not one person's circle , It's the circle of technicians 】

   Interested parties can scan the following QR code or view the left navigation bar to enter the technical circle .

版权声明
本文为[It learning diary]所创,转载请带上原文链接,感谢
https://chowdera.com/2021/10/20211002145946155R.html

随机推荐