File upload and download tool based on Apache FTP implementation

Source: Internet
Author: User
Tags create directory ftp file ftp login getmessage save file free ftp stringbuffer

Based on the Apache FTP implementation of the File upload download tool, upload files need to consider the following issues:

(1) Whether there is a directory for the FTP server, if the directory does not exist, you need to create a directory.

(2), to determine whether the upload file already exists, if there is a need to delete overwrite upload or continue to pass.

The following example code (note: The continuation function is not implemented).

Package com.scengine.wtms.utils.ftp;
Import Java.io.ByteArrayOutputStream;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import Java.io.PrintWriter;
Import java.net.SocketException;
Import Java.net.URLEncoder;
Import Javax.servlet.http.HttpServletResponse;
Import Org.apache.commons.net.PrintCommandListener;
Import Org.apache.commons.net.ftp.FTP;
Import org.apache.commons.net.ftp.FTPClient;
Import Org.apache.commons.net.ftp.FTPClientConfig;
Import Org.apache.commons.net.ftp.FTPFile;

Import org.apache.commons.net.ftp.FTPReply;

Import Com.scengine.wtms.utils.Log;

	public class Oldfashionedftp {private ftpclient ftp;
		The/** * Object construction setting outputs the commands used in the procedure to the console/public oldfashionedftp () {ftp = new ftpclient ();
	This.ftp.addProtocolCommandListener (New Printcommandlistener) (New PrintWriter (System.out)); /** * User FTP Account login * * @param URL * FTP address
	 * @param Port * FTP ports * @param username * User name * @param password * password * @r Eturn True/false Success/failure * @throws socketexception * @throws IOException/Private boolean login (String url, int por
		T, string Username, string password) throws SocketException, IOException {int reply; 1.

		Connect FTP server//If the default port is used, you can use the Ftp.connect (URL) way to directly connect the FTP server ftp.connect (URL, port); 2.
		Set the encoding//the following three lines of code must be, and can not change the encoding format, otherwise can not correctly download the Chinese file ftp.setcontrolencoding ("UTF-8");
		Ftpclientconfig conf = new Ftpclientconfig (FTPCLIENTCONFIG.SYST_NT);

		Conf.setserverlanguagecode ("en"); 3.

		Login to FTP ftp.login (username, password);

		See the return value is not 230, if it is, the landing success Reply = Ftp.getreplycode (); The return value starting with 2 will be true if (!).
			Ftpreply.ispositivecompletion (Reply)) {ftp.disconnect ();
			Log.getlogger (This.getclass ()). info (">>>>>>>>>>>>>>>> connection Server failed!");
		return false; } Log.getlogger (This.getclass ()). info (">>≫>>>>>>>>>>>>>> Landing Server Success! ");
	return true;
			/** * Free FTP/public void disconnect () {if (ftp.isavailable ()) {try {ftp.logout ();//Exit FTP
			catch (IOException e) {Log.getlogger (This.getclass ()). Error ("FTP Login Exit Exception:" + E.getmessage ());
			} if (ftp.isconnected ()) {try {//disconnect ftp.disconnect ();
			catch (IOException e) {Log.getlogger (This.getclass ()). Error ("FTP Disconnect exception:" + E.getmessage ()); /** * FTP File Upload * * @param URL * FTP address * @param port * FTP port * @param userna Me * FTP user name * @param password * FTP password * @param localadr * Upload file name * @param Remo TEADR * Specified FTP directory * @return * @throws IOException/public boolean uploadfile (String url, int port, St Ring Username, string password, string Localadr, String remoteadr) throws IOException {//Initial upload failed Boolean success = false;
		/****** Verify user login information *****/try {success = login (URL, port, username, password); Log.getlogger (This.getclass ()). Info ("FTP User login:" + (success?)
			"Success!": "Failure!");
			if (!success) {return success;
			The catch (IOException e) {Log.getlogger (This.getclass ()). Error ("Upload file exception:" + E.getmessage ());
		return success;

		//Set Passivemode transmission Ftp.enterlocalpassivemode ();

		Set FTP file type is binary, if the default of this sentence transmission txt normal but pictures and other formats of the file transfer appear garbled ftp.setfiletype (Ftp.binary_file_type);

		/***** the processing of remote directories ******/String remotefilename = Remoteadr;
			if (Remoteadr.contains ("/")) {remotefilename = remoteadr.substring (Remoteadr.lastindexof ("/") + 1);

			String directory = remoteadr.substring (0, Remoteadr.lastindexof ("/") + 1); if (!directory.equalsignorecase () &&!ftp.changeworkingdirectory (directory)) {//If the remote directory does not exist, recursively creates the remote server mesh

				Record int start = 0, end = 0;
				if (Directory.startswith ("/")) {start = 1;
				else {start = 0; } end = DirecTory.indexof ("/", start);

					while (true) {String subdirectory = remoteadr.substring (start, end); if (!ftp.changeworkingdirectory (subdirectory)) {if (Ftp.makedirectory (subdirectory)) {Ftp.chan

						Geworkingdirectory (subdirectory);
							else {Log.getlogger (This.getclass ()). info ("Create directory Failed");
						return false;
					} start = end + 1;
					End = Directory.indexof ("/", start);
					Check that all directories are created if (end <= start) {break;
		/***** Execute File Upload ******/inputstream input = null;
			try {file F = new file (LOCALADR);

			Get the corresponding file list of the directory ftpfile[] fs = Ftp.listfiles (Remotefilename);

			Log.getlogger (This.getclass ()). Info ("Number of uploaded files: + fs.length +", file name: "+ Localadr);"
			input = new FileInputStream (f);
			
		Save file Remotefilename success = Ftp.storefile (remotefilename, input);
			The catch (IOException e) {if (input!= null) input.close (); Log.getlogger (This.getclass (). info ("Upload file failed:" + e.getmessage ());
			finally {if (input!= null) input.close ();
			This.disconnect (); Log.getlogger (This.getclass ()). info ("Save ID >>>" + success + "file name:" + Localadr + (success?)
		Upload success! ":" Upload failed! ");
	return success;
	 /** * Delete FTP files and directories * * @param URL * FTP address * @param port * FTP Port * @param username            * User name * @param password * password * @param remoteadr * File path * @param localadr * File name * @return True/false Success/Failure/public boolean deletedirectory (string url, int port, string username, S

		Tring Password, String Remoteadr) {Boolean success = false;
			try {success = login (URL, port, username, password); Log.getlogger (This.getclass ()). Info ("FTP User login:" + (success?)
			"Success!": "Failure!");
			if (!success) {return success;

			}//string remoteadr_ = new String (remoteadr.getbytes ("UTF-8"), "iso-8859-1"); Go to the specified upload directory Ftp.changeworkingdirectOry (REMOTEADR); ftpfile[] fs = Ftp.listfiles ();

			Get the corresponding file list of the directory if (fs.length>0) {success = Ftp.removedirectory (REMOTEADR);
		} catch (IOException e) {Log.getlogger (This.getclass ()). Error (E.getmessage ());
		finally {this.disconnect ();
	return success;            /** * Delete ftp file * * @param URL * FTP address * @param port * FTP Port * @param username * Username * @param password * password * @param remoteadr * File path * @return True/false success/Loss Fail/public boolean deletefile (string url, int port, string username, string password, string Remoteadr) {Boolean s

		Uccess = false;
			try {success = login (URL, port, username, password); Log.getlogger (This.getclass ()). Info ("FTP User login:" + (success?)
			"Success!": "Failure!");
			if (!success) {return success;

			}//string remoteadr_ = new String (remoteadr.getbytes ("UTF-8"), "iso-8859-1"); Get the corresponding file list of the directory ftpfile[] fs = Ftp.listfiles (rEMOTEADR);;
			if (fs.length>0) {//Remoteadr_->remoteadr success =ftp.deletefile (REMOTEADR);
		} catch (IOException e) {Log.getlogger (This.getclass ()). Error (E.getmessage ());
		finally {this.disconnect ();
	return success;            /** * Download FTP file * * @param URL * FPT Address * @param port * FTP Port * @param username *
	 User name * @param password * password * @param remoteremoteadr * Remote path * @param localadr * File name * @param outputstream file output stream * @param response * HTTP response * @return True/false success/Failure * /Public boolean downfile (string url, int port, string username, string password, string Remoteremoteadr, String Localadr
		, HttpServletResponse response) {Boolean success = false;
			try {success = login (URL, port, username, password); Log.getlogger (This.getclass ()). Info ("FTP User login:" + (success?)
			"Success!": "Failure!"); if (!success) {return success;
			//Transfer to FTP server directory ftp.changeworkingdirectory (REMOTEREMOTEADR);
			
			Get the corresponding file list of the directory ftpfile[] fs = Ftp.listfiles (); for (Ftpfile ftpfile:fs) {if (Ftpfile.getname (). Equals (Localadr)) {//This is the key code response that pops up the download dialog box.
					SetHeader ("Content-disposition", "attachment;localadr=" + urlencoder.encode (Localadr, "UTF-8"));
					Save the file to the output stream OutputStream file F=new file (LOCALADR);
					OutputStream os=new FileOutputStream (f);
					Ftp.retrievefile (New String (Ftpfile.getname (). GetBytes ("UTF-8"), "iso-8859-1"), OS);
					Os.flush ();
				Os.close ();
		} success = true;
		catch (IOException e) {e.printstacktrace ();
		finally {this.disconnect ();
	return success;
	 /** * Read FTP file content * * @param URL * FPT Address * @param port * FTP Port * @param username 
	 * User name * @param password * password * @param remoteremoteadr * Remote path * @param localadr * File name * @return string file content */public string readfilecontent (string url, int port, string username, string password, string remo
		Teremoteadr, String localadr) {string content = null;
			try {Boolean success = login (URL, port, username, password); Log.getlogger (This.getclass ()). Info ("FTP User login:" + (success?)
			"Success!": "Failure!"); 
				
				if (success) {//Transfer to the FTP server directory ftp.changeworkingdirectory (REMOTEREMOTEADR);
				
				Get the corresponding file list of the directory ftpfile[] fs = Ftp.listfiles (); for (Ftpfile ftpfile:fs) {if (Ftpfile.getname (). Equals (Localadr)) {//This is the key code that pops up the Download dialog box//Will
						File is saved to the output stream OutputStream file F=new file (LOCALADR);
						Ftp.retrievefile (New String (Ftpfile.getname (). GetBytes ("UTF-8"), "Iso-8859-1"), new FileOutputStream (f));
						Bytearrayoutputstream BOS = new Bytearrayoutputstream ();
						Ftp.retrievefile (Ftpfile.getname (), BOS);
						Bos.flush ();

						Bos.close ();
					Content = new String (Bos.tobytearray (), "UTF-8"); }
				}
			}
		catch (IOException e) {Log.getlogger (ftputils.class). Error (E.getmessage ()); 
		finally {this.disconnect ();
	} return content; /** * The method of determining whether the duplicate name is * * @param localadr * filename * @param fs * file List array * @return * * p Ublic Static Boolean isdirexist (String Localadr, ftpfile[] fs) {for (Ftpfile ftpfile:fs) {if (Ftpfile.getname) (
			). Equals (Localadr)) {return true;
	return false;            /** * The name of the new file is generated according to the result of the duplicate names +[n], n represents the number * * @param localadr * * File name * @param FS *
		FTP file list * @return */public static String rename (string Localadr, ftpfile[] fs) {int n = 0;
		Create a variable string object that is the StringBuffer object, and pay the Localadr value to the object StringBuffer localadr_ = new StringBuffer ("");

		Localadr_ = Localadr_.append (LOCALADR);
			Renamed with duplicate names, traversing files with the same name while (Isdirexist (localadr_.tostring (), FS)) {n++;
			String a = "[" + N + "]";
	The last place where the decimal point appears int b = Localadr_.lastindexof (".");		The position int c = Localadr_.lastindexof ("[") where the Last "[" appears];
			if (c < 0) {c = b;
			}//File name StringBuffer name = new StringBuffer (localadr_.substring (0, c));
			The name of the suffix stringbuffer suffix = new StringBuffer (localadr_.substring (b + 1)); Localadr_ = Name.append (a). Append (".").
		Append (suffix);
	return localadr_.tostring ();
		public static void Main (string[] args) {oldfashionedftp ftp = new Oldfashionedftp (); try {ftp.uploadfile ("192.168.1.200", "Duser", "HTPDuserXP32", "C:\\users\\administrator\\desktop\\backgroud_cha
		Nge.html ","/htmls/backgroud_change.html ");
		catch (IOException e) {Log.getlogger (oldfashionedftp.class). Error (E.getmessage ());
 }
	}

}

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.