Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to upload FTP files with Java

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to use Java to upload FTP files", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to upload FTP files with Java.

FTP, full name File Transefer Protocol, File transfer Protocol, uses a set of standard protocols for file transfer over the network.

Configure the FTP file server

Take Ubuntu as an example

Brief introduction of two modes of FTP

PORT (active mode)

In the first step, the FTP client randomly selects a port p1 greater than 1024, and sends a request through this port to connect to port 21 of the FTP server to establish a TCP connection. In FTP, this connection is called a control connection. After the connection is successfully established, the FTP client will send a port command, and then the FTP client will monitor its p1room1 port. When the FTP server receives the port command, it initiates a request to establish a TCP connection from its port 20 to the p1 port of the FTP client. This connection is called a data connection, which is used to send data. After the data transmission is completed, the data connection is closed, and the control connection remains open.

Passive (passive mode)

It is similar to active mode when establishing a control connection, but instead of a Port command, a Pasv command is sent after the connection is established. After the FTP server receives the Pasv command, it randomly opens a temporary port (also called free port, the port number is greater than 1023 and less than 65535) and notifies the client of the request to transfer data on this port. The FTP client sends a request to connect to the FTP server this port. After the connection is successfully established, the FTP server will transfer data through this port and the data connection will be closed immediately after the data transmission is completed, and the control connection will remain open.

Note! Because many firewalls are not allowed to accept externally initiated connections when they are set up, many FTP clients behind the firewall or intranet do not support active mode because the server cannot pass through the firewall or connect to the client behind the NAT. So you need to turn on passive mode when uploading files!

1. Install vsftpd

Apt-get install vsftpd

2. Configure vsftpd

Vi / etc/vsftpd.conf

The following is a detailed description of the vsftpd configuration

(1), core configuration

Local_enable=YES / / allow local users to log in to write_enable=YES / / write permissions of local users local_umask=022 / / use local file permissions of FTP. Default is 077. Generally, it is set to 022 pam_service_name=vsftpd / / Authentication mode connect_from_port_20=YES / / data connection listen=yes of FTP data port enabled / / run listen_port=23 / / modify connection port as an independent FTP service

(2) Anonymous login settings

Anonymous_enable=NO / / whether anonymous login is allowed. It is recommended not to allow anon_upload_enable=YES / / if anonymous login is allowed, whether to enable anonymous upload permission anon_mkdir_write_enable=YES / / if anonymous login is allowed, whether to establish a folder anonymously and upload files within the folder anon_other_write_enable=yes / / if anonymous login is allowed Anonymous account can have deletion permission anon_world_readable_only=no / / if anonymous login is allowed, anonymous download permission is Other, directory / file attribute can be set to control anon_max_rate=30000 / / if anonymous login is allowed, anonymous user transfer rate is limited, unit bite

(3) restrict login

Userlist_enable=yes / / use userlist to restrict user access to userlist_deny=no / / people in the list are not allowed to access the path where the userlist_file=/etc/vsftpd/userlist_deny.chroot / / restricted list file is placed

(4) restricted catalogue

Chroot_local_user=yes / / restrict all users to home directory chroot_list_enable=YES / / call restrict home directory user list chroot_list_file=/etc/vsftpd/chroot_list / / restrict the path of user list in home directory

(5), log settings

Xferlog_file=/var/log/vsftpd.log / / Log file path set xferlog_std_format=YES / / use standard log format

(6) Security settings

Idle_session_timeout=600 / / user idle timeout, unit second data_connection_timeout=120 / / data connection idle timeout, unit second accept_timeout=60 / / disconnect the client after 1 minute idle local_max_rate=10000 / / local user transfer rate, maximum number of connections per bitemax_clients=100 / / FTP max_per_ip= 3 / / maximum number of connections per IP

(7), passive mode setting

Pasv_enable=yes / / whether to open an account in passive mode pasv_min_port=3000 / / passive mode minimum port pasv_max_port=5000 / / passive mode maximum port

In fact, if you configure one, you can upload files.

Write_enable=YES, just let go.

I have been working in this passive mode all day, but I can't upload the picture, only 0kb, and I still can't find the reason. Hey.

3. Restart the startup service

Service vsftpd restart

4. Log in

2. Java uploads files to FTP

Then upload a file that is relatively simple to write.

/ * Description: upload files to FTP server * @ param host FTP server hostname * @ param port FTP server port * @ param username FTP login account * @ param password FTP login password * @ param basePath FTP server base directory * @ param filePath FTP server file storage path. For example, it is stored by date: / 2018-01-01. The path of the file is the file name * @ param input input stream * @ return uploaded to the FTP server by basePath+filePath * @ param input. True is returned successfully, otherwise false * / public static boolean uploadFile (String host, int port, String username, String password, String basePath, String filePath, String filename, InputStream input) {boolean result = false; FTPClient ftp = new FTPClient () Try {int reply; / / Connect to the FTP server / / if you use the default port, you can directly connect to the FTP server ftp.connect (host, port) using ftp.connect (host); / / Log in to ftp.login (username, password); reply = ftp.getReplyCode () / / get the status code if (! FTPReply.isPositiveCompletion (reply)) {ftp.disconnect (); / / end the connection return result; / / determine whether the login is successful according to the status code} / / set the client to passive mode ftp.enterLocalPassiveMode () / / switch to upload directory if (! ftp.changeWorkingDirectory (basePath+filePath)) {/ / create directory String [] dirs = filePath.split ("/") if the directory does not exist; String tempPath = basePath; for (String dir: dirs) {if (null = = dir | | ".equals (dir)) continue TempPath + = "/" + dir; if (! ftp.changeWorkingDirectory (tempPath)) {if (! ftp.makeDirectory (tempPath)) {return result;} else {ftp.changeWorkingDirectory (tempPath) } / / set the type of uploaded file to binary type ftp.setFileType (FTP.BINARY_FILE_TYPE); / / upload file successfully true failed false if (! ftp.storeFile (filename, input)) {return result } input.close (); ftp.logout (); result = true;} catch (IOException e) {e.printStackTrace ();} finally {if (ftp.isConnected ()) {try {ftp.disconnect () } catch (IOException ioe) {} return result } / * Description: download the file from the FTP server * @ param host FTP server hostname * @ param port FTP server port * @ param username FTP login account * @ param password FTP login password * @ relative path on the param remotePath FTP server * @ param fileName to download the document name * @ param localPath Save to the local path * @ return * / public static boolean downloadFile (String host Int port, String username, String password, String remotePath, String fileName, String localPath) {boolean result = false / / create object FTPClient ftp = new FTPClient (); try {int reply; / / establish a link / / if you use the default port, you can directly connect to the FTP server ftp.connect (host, port) using ftp.connect (host); / / Log in to ftp.login (username, password) Reply = ftp.getReplyCode (); if (! FTPReply.isPositiveCompletion (reply)) {ftp.disconnect (); return result;} / / sets the client to passive mode ftp.enterLocalPassiveMode (); ftp.changeWorkingDirectory (remotePath) / / transfer to the FTP server directory FTPFile [] fs = ftp.listFiles (); for (FTPFile ff: fs) {if (ff.getName (). Equals (fileName)) {File localFile = new File (localPath + "/" + ff.getName ()); OutputStream is = new FileOutputStream (localFile) Ftp.retrieveFile (ff.getName (), is); is.close ();} ftp.logout (); result = true;} catch (IOException e) {e.printStackTrace () } finally {if (ftp.isConnected ()) {try {ftp.disconnect ();} catch (IOException ioe) {} return result;}

Test class

InputStream inputStream = new FileInputStream (new File ("D:/mine/x.jpg")); / / uuid generates a unique name that claims that uuid generated by the same dimension will never repeat String uuid = UUID.randomUUID (). ToString (). ReplaceAll ("-", "); FTPTools.uploadFile (" 192.168.1.242 ", 21," Q "," Q "," / home/q/ "," / ", uuid+" get file suffix ", inputStream)

The native ftp of Apache. If you find that you are connected to ftp but the file upload is not successful, nine times out of ten there is something wrong with the Vsftpd configuration.

At this point, I believe you have a deeper understanding of "how to use Java to upload FTP files". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report