<%@ page import="java.io.File"%>
<%@ page import="java.io.FileInputStream"%>
<%@ page import="java.io.FileOutputStream"%>
<%@ page import="java.io.IOException"%>
<%@ page import="org.apache.commons.net.ftp.FTP"%>
<%@ page import="org.apache.commons.net.ftp.FTPClient"%>
<%@ page import="org.apache.commons.net.ftp.FTPFile"%>
<%@ page import="org.apache.commons.net.ftp.FTPReply"%>
<%
String server = "192.168.1.2";
String username = "andowson";
String password = "changeit";
String directory = "download";
String filename = "C:\\Users\\Andowson\\Desktop\\jspSmartUpload.zip";
File filePut = new File(filename);
String filename2 = "C:\\Users\\Andowson\\Desktop\\commons-net-1.4.1.zip";
File fileGet = new File(filename2);
String filename3 = "jdk-6u3-windows-i586-p.exe";
FTPClient ftp = new FTPClient();
// We want to timeout if a response takes longer than 30 seconds
ftp.setDefaultTimeout(30000);
try {
int reply;
ftp.connect(server);
System.out.println("Connected to " + server + ".");
System.out.print(ftp.getReplyString());
// After connection attempt, you should check the reply code to verify
// success.
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
System.err.println("FTP server refused connection.");
return;
}
// transfer files
if (ftp.login(username, password)) {
long totalSize = 0L;
for (FTPFile file : ftp.listFiles(directory)) {
System.out.printf("%s %s [%d bytes]\n",
(file.isDirectory() ? "[D]" : " "), file.getName(), file.getSize());
if (!file.isDirectory()) {
totalSize += file.getSize();
}
}
System.out.println("totalSize = " + totalSize/(1024 * 1024) + "MB");
// PASV
ftp.enterLocalPassiveMode();
// CWD
ftp.changeWorkingDirectory(directory);
// PWD
System.out.println(ftp.printWorkingDirectory());
// TYPE I
ftp.setFileType(FTP.BINARY_FILE_TYPE);
// PUT
ftp.storeFile(filePut.getName(), new FileInputStream(filePut));
// GET
ftp.retrieveFile(fileGet.getName(), new FileOutputStream(fileGet));
// DELE
ftp.deleteFile(filename3);
}
ftp.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
// do nothing
}
}
}
%>
檔案名稱 | ftptest.jsp |
描述 | FTP Client 範例程式 |
檔案大小 | 2 Kbytes |
下載次數 | 88 次 |
下載 |
<%@ page import="java.io.File"%>
<%@ page import="java.util.Locale"%>
<%@ page import="com.enterprisedt.net.ftp.FTPClient"%>
<%@ page import="com.enterprisedt.net.ftp.FTPConnectMode"%>
<%@ page import="com.enterprisedt.net.ftp.FTPException"%>
<%@ page import="com.enterprisedt.net.ftp.FTPFile"%>
<%@ page import="com.enterprisedt.net.ftp.FTPMessageCollector"%>
<%@ page import="com.enterprisedt.net.ftp.FTPReply"%>
<%@ page import="com.enterprisedt.net.ftp.FTPTransferType"%>
<%@ page import="com.enterprisedt.net.ftp.UnixFileParser"%>
<%
// assign args to make it clear
String server = "192.168.1.2";
String username = "andowson";
String password = "changeit";
String directory = "download";
String filename = "C:\\Users\\Andowson\\Desktop\\jspSmartUpload.zip";
File filePut = new File(filename);
String filename2 = "C:\\Users\\Andowson\\Desktop\\commons-net-1.4.1.zip";
File fileGet = new File(filename2);
String filename3 = "jdk-6u3-windows-i586-p.exe";
FTPClient ftp = new FTPClient();
// We want to timeout if a response takes longer than 30 seconds
ftp.setTimeout(30000);
try {
// set up client
ftp.setRemoteHost(server);
FTPMessageCollector listener = new FTPMessageCollector();
ftp.setMessageListener(listener);
// connect
ftp.connect();
System.out.println("Connected to " + server + ".");
String messages = listener.getLog();
System.out.print(messages);
FTPReply reply = ftp.getLastReply();
if (reply != null) {
System.out.print(reply.getRawReply());
//String replyCode = reply.getReplyCode();
System.out.print(reply.getReplyCode());
}
// login
ftp.login(username, password);
// set up passive BINARY transfers
ftp.setConnectMode(FTPConnectMode.PASV);
// get directory and print it to console
UnixFileParser ufp = new UnixFileParser();
ufp.setLocale(new Locale("en", "US"));
String[] files = ftp.dir(directory, true);
long totalSize = 0L;
for (int i = 0; i < files.length; i++) {
//System.out.println(files[i]);
FTPFile file = ufp.parse(files[i]);
System.out.printf("%s %s [%d bytes]\n",
(file.isDir() ? "[D]" : " "), file.getName(), file.size());
if (!file.isDir()) {
totalSize += file.size();
}
}
System.out.println("totalSize = " + totalSize / (1024 * 1024) + "MB");
ftp.chdir(directory);
System.out.println(ftp.pwd());
ftp.setType(FTPTransferType.BINARY);
// copy file to server
ftp.put(filename, filePut.getName());
// copy file from server
ftp.get(filename2, fileGet.getName());
// delete file from server
ftp.delete(filename3);
// Shut down client
ftp.quit();
} catch (FTPException e) {
e.printStackTrace();
} finally {
if (ftp.connected()) {
try {
ftp.quit();
} catch (Exception e) {
// do nothing
}
}
}
%>
檔案名稱 | ftpdemo.jsp |
描述 | FTP Demo Using Enterprise Distributed Technologies FTP for Java component |
檔案大小 | 3 Kbytes |
下載次數 | 30 次 |
下載 |
viva wrote:不好意思請問一下
ftptest.jsp裡有這一行 ftp.setDefaultTimeout(30000);
設定這時間是什麼意思?
viva wrote:不好意思,在請教一下
ftp.setDefaultPort(21);
這語法的用意是什麼?為何會設21與13?
若不加這行,也OK嗎?
viva wrote:
在請教一下...(我好像問題好多,不知道會不會造成你困擾)
我已經寫好我自己要使用的FTP程式...
但....如果在FTP設定伺服器種類設為FTPES-透過外顯式TLS/SSL的FTP
那我的FTP程式還連的上嗎?
<%@ page contentType="text/html; charset=BIG5" %>
<jsp:useBean id="dbOprBean" scope="page" class="com.gemmyplanet.dbbean.DBOperationBean" />
<jsp:setProperty name="dbOprBean" property="*" />
<%@ include file="inc_common_parameters.jsp" %>
<%@ include file="inc_common_fun_ecindp.jsp" %>
<%@ include file="inc_common_fun_doc.jsp" %>
<%@ include file="inc_gp_fun_mysql5.jsp" %>
<%@ page import="java.io.*"%>
<%@ page import="java.util.*"%>
<%@ page import="org.apache.commons.net.ftp.*"%>
<%
/////////////////////////////////////////////////
// 接收參數
//////////////////////////////////////////////////
String GPBID = null;
try{
GPBID = request.getParameter("GPBID");
if( GPBID == null )
gERR = 1;
}catch(Exception e) {
gERR = 1;
gERRMSG = "lack parameter";
}
/////////////////////////////////////////////////
// 宣告參數
//////////////////////////////////////////////////
String server = "主機名稱";
String login = "帳號";
String password = "密碼";
String Ftp_Upload_FileName = ""; //上傳檔名
GPDatabaseTK gpdb = new GPDatabaseTK(dbOprBean, "BIG5");
GPJAVATK gpjtk = new GPJAVATK(gpdb);
/////////////////////////////////////////////////
// 取出檔名並重新命名
//////////////////////////////////////////////////
if( gERR == 0 ) {
BANNERINFO bannerinfo = gpjtk.getBannerFilename( GPBID ); //以 GPBID 抓 Banner 檔名
if( bannerinfo != null ) {
String[] tokens = (bannerinfo.mFILENAME).split("\\/");
Ftp_Upload_FileName = tokens[(tokens.length)-1];
/////////////////////////////////////////////////
// 連接 FTP
//////////////////////////////////////////////////
FTPClient ftp = new FTPClient(); //連接、登錄服務器
ftp.setDefaultTimeout(30000); //等候連線的對方回應ACK的時間
try {
int reply;
String UploadCatalog = "/public_html/res"; //上傳到哪個目錄下/public_html/res
ftp.setDefaultPort(21);
ftp.connect( server ); //連接FTP
ftp.login( login, password ); //登入
ftp.changeWorkingDirectory( UploadCatalog ); //當下在 Ftp 服務器上的工作目錄
reply = ftp.getReplyCode();
if ( !FTPReply.isPositiveCompletion(reply) ) { //判斷是否連線成功?
ftp.logout(); //退出 FTP 服務器
ftp.disconnect(); //關閉連接
%> <script language=javascript>
window.alert("FTP連線失敗!");
location.href="http://失敗後返回的網址";
</script>
<%
} else {
/*
FTPFile[] list = ftp.listFiles(); //獲得當前 FTP 服務器工作目錄中的文件列表
for (int i = 0; i < list.length; i++) {
String name = list[i].getName(); //取得檔名
out.println("FTP檔名 : " + name+"<br>");
}
*/
/////////////////////////////////////////////////
// 檔案上傳
//////////////////////////////////////////////////
try {
int file_size;
//圖檔路徑 "C:/Program Files/Apache Group/Tomcat 4.1/webapps/gp_image/res/"+Ftp_Upload_FileName
String path = gWEBROOT+"/gp_image/res/"+Ftp_Upload_FileName;
File file = new File(path);
if( file.exists() ) {
FileInputStream fis = new FileInputStream(file);
ftp.setBufferSize(1024);
ftp.setFileType(ftp.BINARY_FILE_TYPE); //設置文件類型(二進制),圖檔都用BINARY_FILE_TYPE
ftp.storeFile( Ftp_Upload_FileName , fis );
fis.close(); //關閉串流
/////////////////////////////////////////////////
// 檔案下載
//////////////////////////////////////////////////
/*
String remoteFileName = "/ftp_test/01.jpg";
File file = new File("c:/999999999.jpg");
FileOutputStream fos = new FileOutputStream(file);
ftp.setBufferSize(1024);
ftp.setFileType(ftp.BINARY_FILE_TYPE); //設置文件類型(二進制),圖檔都用BINARY_FILE_TYPE
ftp.retrieveFile(remoteFileName, fos);
fos.close();
if( file.exists() ) {
out.println("檔案存在<br>");
} else {
out.println("檔案不存在");
}
*/
if (ftp != null && ftp.isConnected()) {
ftp.logout(); //退出 FTP 服務器
ftp.disconnect(); //關閉連接
}
%> <script language=javascript>
window.alert("上傳成功!");
location.href="http://成功後返回的網址";
</script>
<% } else {
if (ftp != null && ftp.isConnected()) {
ftp.logout(); //退出 FTP 服務器
ftp.disconnect(); //關閉連接
}
%> <script language=javascript>
window.alert("檔案不存在!");
location.href="http://返回網址";
</script>
<% }
} catch (IOException e) {
%> <script language=javascript>window.alert("FTP上傳失敗!<%=e.getMessage()%>!");</script>
<% //e.printStackTrace();
//throw new RuntimeException("FTP客戶端錯誤!", e);
}
}
} catch (Exception e) {
%> <script language=javascript>window.alert("FTP上傳失敗!<%=e.getMessage()%>!請重試!");</script>
<% }
}
}
%>
if (ftp.login(username, password)) {
boolean dirExist = false;
String dirA = "upload";
FTPFile[] files = ftp.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory() && files[i].getName().equals(dirA)) {
dirExist = true;
break;
}
}
out.println("directory " + dirA + " exists? " + dirExist);
if (!dirExist) {
ftp.makeDirectory(dirA);
}
}
<%@ page import="java.io.File"%>
<%@ page import="java.io.IOException"%>
<%@ page import="org.ftp4che.*"%>
<%@ page import="org.ftp4che.util.ftpfile.*"%>
<%@ page import="org.ftp4che.exception.*"%>
<%@ page import="org.ftp4che.impl.SecureFTPConnection"%>
<%
String server = "192.168.1.2";
String username = "andowson";
String password = "changeit";
String directory = "download";
String filename = "C:\\Users\\Andowson\\Desktop\\jspSmartUpload.zip";
File filePut = new File(filename);
String filename2 = "C:\\Users\\Andowson\\Desktop\\commons-net-1.4.1.zip";
File fileGet = new File(filename2);
String filename3 = "jdk-6u3-windows-i586-p.exe";
FTPConnection ftp = null;
try {
ftp = FTPConnectionFactory.getInstance(server, 21, username, password, FTPConnection.AUTH_TLS_FTP_CONNECTION, true);
ftp.connect();
System.out.println("Connected to " + server + ".");
// transfer files
long totalSize = 0L;
for (FTPFile file : ftp.getDirectoryListing(directory)) {
System.out.printf("%s %s [%d bytes]\n",
(file.isDirectory() ? "[D]" : " "), file.getName(), file.getSize());
if (!file.isDirectory()) {
totalSize += file.getSize();
}
}
System.out.println("totalSize = " + totalSize/(1024 * 1024) + "MB");
// PASV
ftp.setPassiveMode(true);
// CWD
ftp.changeDirectory(directory);
// PWD
System.out.println(ftp.getWorkDirectory());
// PUT
FTPFile fromFile = new FTPFile(filePut);
FTPFile toFile = new FTPFile(new File(filePut.getName()));
ftp.uploadFile(fromFile, toFile);
// GET
fromFile = new FTPFile(new File(fileGet.getName()));
toFile = new FTPFile(fileGet);
ftp.downloadFile(fromFile, toFile);
// DELE
ftp.deleteFile(new FTPFile(new File(filename3)));
} catch (NotConnectedException nce) {
nce.printStackTrace();
} catch (FtpFileNotFoundException ffnfe) {
ffnfe.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp != null) {
ftp.disconnect();
}
}
%>
檔案名稱 | ftp4che.jsp |
描述 | FTPS檔案傳輸程式 |
檔案大小 | 2 Kbytes |
下載次數 | 19 次 |
下載 |
<%@ page import="java.io.File"%>
<%@ page import="java.io.FileInputStream"%>
<%@ page import="java.io.FileOutputStream"%>
<%@ page import="java.util.Properties"%>
<%@ page import="java.util.Vector"%>
<%@ page import="com.jcraft.jsch.Channel"%>
<%@ page import="com.jcraft.jsch.ChannelSftp"%>
<%@ page import="com.jcraft.jsch.JSch"%>
<%@ page import="com.jcraft.jsch.Session"%>
<%@ page import="com.jcraft.jsch.ChannelSftp.LsEntry"%>
<%
try {
String host = "192.168.1.2";
int port = 22;
String username = "andowson";
String password = "changeit";
String directory = "/home/andowson/download/";
String uploadFile = "C:\\temp\\upload.txt";
String downloadFile = "C:\\temp\\download.txt";
String deleteFile = "delete.txt";
//
// First Create a JSch session
//
System.out.println("Creating session.");
JSch jsch = new JSch();
ChannelSftp sftp = null;
//
// Now connect and SFTP to the SFTP Server
//
try {
// Create a session sending through our username and password
Session sshSession = jsch.getSession(username, host, port);
System.out.println("Session created.");
sshSession.setPassword(password);
// Security.addProvider(new com.sun.crypto.provider.SunJCE());
//
// Setup Strict HostKeyChecking to no so we don't get the
// unknown host key exception
//
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
System.out.println("Session connected.");
//
// Open the SFTP channel
//
System.out.println("Opening Channel.");
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
System.out.println("Connected to " + host + ".");
} catch (Exception e) {
System.err.println("Unable to connect to FTP server." + e.toString());
throw e;
}
//
// Change to the remote directory
//
System.out.println("Changing to FTP remote dir: " + directory);
// CWD
sftp.cd(directory);
// PWD
System.out.println(sftp.pwd());
//
// Send the file we generated, PUT
//
File filePut = new File(uploadFile);
try {
System.out.println("Storing file as remote filename: " + filePut.getName());
sftp.put(new FileInputStream(filePut), filePut.getName());
} catch (Exception e) {
System.err.println("Storing remote file failed." + e.toString());
throw e;
}
//
// Get the list of files in the remote server directory
//
Vector files = sftp.ls(directory);
//
// Log if we have nothing to download
//
if (files.size() == 0) {
System.out.println("No files are available for download.");
}
//
// Otherwise download all files except for the . and .. entries
//
else {
long totalSize = 0L;
for (int i = 0; i < files.size(); i++) {
LsEntry file = (LsEntry) files.get(i);
if (!file.getFilename().equals(".") && !file.getFilename().equals("..")) {
System.out.printf("%s %s [%d bytes]\n",
(file.getAttrs().isDir() ? "[D]" : " "), file.getFilename(), file.getAttrs().getSize());
if (!file.getAttrs().isDir()) {
totalSize += file.getAttrs().getSize();
}
}
}
System.out.println("totalSize = " + totalSize/(1024 * 1024) + "MB");
//
// Get the file and write it to our local file system, GET
//
System.out.println("Downloading file " + filePut.getName());
File fileGet = new File(downloadFile);
sftp.get(filePut.getName(), new FileOutputStream(fileGet));
//
// Remove the file from the server, DELE
//
System.out.println("Deleting file " + deleteFile);
sftp.rm(deleteFile);
}
//
// Disconnect from the FTP server
//
try {
sftp.quit();
} catch (Exception e) {
System.err.println("Unable to disconnect from FTP server. " + e.toString());
}
} catch (Exception e) {
System.err.println("Error: " + e.toString());
e.printStackTrace();
}
System.out.println("Process Complete.");
%>
檔案名稱 | sftp.jsp |
描述 | Java SFTP範例程式 |
檔案大小 | 4 Kbytes |
下載次數 | 41 次 |
下載 |