Java implements the cross-Server File upload function, and java uploads files

Source: Internet
Author: User
Tags ftp access

Java implements the cross-Server File upload function, and java uploads files

A project was created a few days ago. both the client and the Administrator shared a single server, and the files uploaded by the client were stored on the server's hard disk. Lao long proposed to separate the client from the Administrator. In this case, the storage of attachments uploaded by the user becomes faulty. Obviously, it is unrealistic to store an apk file that is several hundred MB in size to the database. After a half-day query, it is the fastest way to create an ftp server on both ends to transfer files.

The specific process is that the user logs on to the Internet client and uploads the file to the hard disk of the Internet server. At the same time, the file accesses the ftp server of the Intranet administrator server through the Internet server and passes it to the hard disk of the Intranet server. In this way, the Intranet server can encrypt and sign the uploaded files, and then upload the files back to the hard disk of the internet server through ftp for other operations.

The specific tool used for implementation: Serv-U. Serv-U is a tool that facilitates the establishment of ftp servers on windows. After downloading and cracking, set the Ip address, port, account password, disk path that allows ftp access, and Operation permission. Select 127.0.0.1 when testing the IP address on the local machine, and 192.168.0.x when testing the Intranet.

In the java project, I wrote a tool class and used the apache commons-net package to upload, download, and delete functions. Code attached:

Package app. ftp; import java. io. file; import java. io. fileInputStream; import java. io. fileNotFoundException; import java. io. fileOutputStream; import java. io. IOException; import java. io. inputStream; import java. io. outputStream; import org.apache.commons.net. ftp. FTPClient; import org.apache.commons.net. ftp. FTPFile; import org.apache.commons.net. ftp. FTPReply;/*** FTP server tool class **/public class FTPUtils {/*** Upload a file to the FTP server ** @ param url * Server IP Address * @ param port * server port * @ param userName * User Login name * @ param password * User Login password * @ param storePath * Server File Storage path * @ param fileName * Server File Storage name * @ param is * file input stream * @ return * <B> true </B>: uploaded successfully * <br/> * <B> false </B>: Upload Failed */public static boolean storeFile (String url, int port, String userName, String password, string storePath, String fileName, InputStream is) {Boolean result = false; FTPClient ftp = new FTPClient (); try {// connect to the server. If the default port is 21, you can directly connect to ftp through URL. connect (url, port); // log on to the ftp server. login (userName, password); // determines whether the return code is valid if (! FTPReply. isPositiveCompletion (ftp. getReplyCode () {// if it is invalid, disconnect ftp. disconnect (); // The End program return result;} // determines whether the ftp directory exists. If not, create a directory, including creating a multi-level directory String s = "/" + storePath; string [] dirs = s. split ("/"); ftp. changeWorkingDirectory ("/"); // check whether the directory exists in sequence. If the directory does not exist, create the directory for (int I = 1; dirs! = Null & I <dirs. length; I ++) {if (! Ftp. changeWorkingDirectory (dirs [I]) {if (ftp. makeDirectory (dirs [I]) {if (! Ftp. changeWorkingDirectory (dirs [I]) {return false ;}} else {return false ;}}// set the file operation directory ftp. changeWorkingDirectory (storePath); // sets the file type, binary ftp. setFileType (FTPClient. BINARY_FILE_TYPE); // set the buffer size ftp. setBufferSize (3072); // Upload File result = ftp. storeFile (fileName, is); // close the input stream is. close (); // log out of the ftp server. logout ();} catch (IOException e) {e. printStackTrace ();} finally {try {// determine whether the input stream exists if (Null! = Is) {// close the input stream is. close () ;}// determine whether the connection exists if (ftp. isConnected () {// disconnect ftp. disconnect () ;}} catch (IOException e) {e. printStackTrace () ;}} return result ;} /*** download the file from the FTP server to the local ** @ param url * Server IP Address * @ param port * server port * @ param userName * User Login name * @ param password * User Login password * @ param remotePath * Server File Storage path * @ param fileName * Server File Storage name * @ param localPath * local file storage path * @ return * <B> true </B>: Download successful * <br/> * <B> false </B>: Download failed */public static boolean retrieveFile (String url, int port, String userName, String password, string remotePath, String fileName, String localPath) {boolean result = false; FTPClient ftp = new FTPClient (); OutputStream OS = null; try {// connect to the server, when the default port is 21, you can directly connect to ftp through URL. connect (url, port); // log on to the ftp server. login (userName, password); // determines whether the return code is valid if (! FTPReply. isPositiveCompletion (ftp. getReplyCode () {// if it is invalid, disconnect ftp. disconnect (); // The End program return result;} // sets the file operation directory ftp. changeWorkingDirectory (remotePath); // sets the file type, binary ftp. setFileType (FTPClient. BINARY_FILE_TYPE); // set the buffer size ftp. setBufferSize (3072); // set the character encoding ftp. setControlEncoding ("UTF-8"); // construct the local File object File localFile = new File (localPath + "/" + fileName ); // obtain the names of all objects in the file operation directory String [] remoteNa Mes = ftp. listNames (); // cyclically compares the file name to determine whether the file name to be downloaded contains the for (String remoteName: remoteNames) {if (fileName. equals (remoteName) {result = true ;}// when the file name comparison is successful, enter the download process if (result) {// construct file output stream OS = new FileOutputStream (localFile); // download file result = ftp. retrieveFile (fileName, OS); // close the output stream OS. close ();} // log out of the ftp server. logout ();} catch (IOException e) {e. printStackTrace ();} finally {try {// determine whether the output stream exists If (null! = OS) {// close the output stream OS. close () ;}// determine whether the connection exists if (ftp. isConnected () {// disconnect ftp. disconnect () ;}} catch (IOException e) {e. printStackTrace () ;}} return result ;} /*** delete the file from the FTP server ** @ param url * Server IP Address * @ param port * server port * @ param userName * User Login name * @ param password * User Login password * @ param remotePath * Server File Storage path * @ param fileName * Server File Storage name * @ return * <B> true </B>: deleted successfully * <br/> * <B> false </B>: deletion failed. */Public static boolean deleteFile (String url, int port, String userName, String password, String remotePath, String fileName) {boolean result = false; FTPClient ftp = new FTPClient (); try {// connect to the server. If the default port is 21, you can directly connect to ftp through URL. connect (url, port); // log on to the ftp server. login (userName, password); // determines whether the return code is valid if (! FTPReply. isPositiveCompletion (ftp. getReplyCode () {// if it is invalid, disconnect ftp. disconnect (); // The End program return result;} // sets the file operation directory ftp. changeWorkingDirectory (remotePath); // sets the file type, binary ftp. setFileType (FTPClient. BINARY_FILE_TYPE); // set the buffer size ftp. setBufferSize (3072); // set the character encoding ftp. setControlEncoding ("UTF-8"); // get all file names in the file operation directory String [] remoteNames = ftp. listNames (); // cyclically compares the file name to determine whether the file name to be downloaded contains the for (String remoteName: remoteNames) {if (fileName. equals (remoteName) {result = true ;}// when the file name comparison is successful, enter the deletion process if (result) {// delete file result = ftp. deleteFile (fileName);} // log out of the ftp server. logout ();} catch (IOException e) {e. printStackTrace ();} finally {try {// determine whether the connection exists if (ftp. isConnected () {// disconnect ftp. disconnect () ;}} catch (IOException e) {e. printStackTrace () ;}} return result;} public static void main (String [] args) throws FileNotFoundException {// try {// FileInputStream FCM = new FileInputStream (new File ("D:/Soft Storage/software toolkit/HTML_Help_WorkShop_1.3_XiaZaiBa.zip"); // System. out. println (storeFile ("192.168.1.2", 21, "admin", "1", "C:/Documents and Settings/Administrator/desktop", RandomUUID. random () + ". zip ", FCM); //} catch (FileNotFoundException e) {// e. printStackTrace (); //} // File file = new File ("C:/Users/freed/Desktop/1.txt "); // InputStream is = new FileInputStream (file); // System. out. println (storeFile ("127.0.0.1", 21, "feili", "feili", "examples", "2.txt", is); // System. out. println (retrieveFile ("127.0.0.1", 21, "feili", "feili", "examples/jsp", "index.html", "C: /Users/freed/Desktop "); // System. out. println (deleteFile ("127.0.0.1", 21, "feili", "feili", "testpath", "1.txt "));}}

Note that when uploading a File, you must first put the File in fileinputstream.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.