當前位置:首頁 » 文件管理 » java實現文件上傳到ftp

java實現文件上傳到ftp

發布時間: 2025-03-18 02:43:25

『壹』 ftpclient怎麼上傳文件

java程序開發中,ftp用的比較多,經常打交道,比如說向FTP伺服器上傳文件、下載文件,現在給大家介紹如何利用jakarta commons中的FTPClient(在commons-net包中)實現上傳文件。
原理就不介紹了,大家直接看代碼
/** * Description: 向FTP伺服器上傳文件 * @Version1.0 Jul 27, 2008 4:31:09 PM by 崔紅保([email protected])創建 * @param url FTP伺服器hostname * @param port FTP伺服器埠 * @param username FTP登錄賬號 * @param password FTP登錄密碼 * @param path FTP伺服器保存目錄 * @param filename 上傳到FTP伺服器上的文件名 * @param input 輸入流 * @return 成功返回true,否則返回false */ publicstaticboolean uploadFile(String url,int port,String username, String password, String path, String filename, InputStream input) { boolean success = false; FTPClient ftp = new FTPClient(); try { int reply; ftp.connect(url, port);//連接FTP伺服器 //如果採用默認埠,可以使用ftp.connect(url)的方式直接連接FTP伺服器 ftp.login(username, password);//登錄 reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return success; } ftp.changeWorkingDirectory(path); ftp.storeFile(filename, input); input.close(); ftp.logout(); success = true; } catch (IOException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return success; }pre/pre /** * Description: 向FTP伺服器上傳文件 * @Version1.0 Jul 27, 2008 4:31:09 PM by 崔紅保([email protected])創建 * @param url FTP伺服器hostname * @param port FTP伺服器埠 * @param username FTP登錄賬號 * @param password FTP登錄密碼 * @param path FTP伺服器保存目錄 * @param filename 上傳到FTP伺服器上的文件名 * @param input 輸入流 * @return 成功返回true,否則返回false */ public static boolean uploadFile(String url,int port,String username, String password, String path, String filename, InputStream input) { boolean success = false; FTPClient ftp = new FTPClient(); try { int reply; ftp.connect(url, port);//連接FTP伺服器 //如果採用默認埠,可以使用ftp.connect(url)的方式直接連接FTP伺服器 ftp.login(username, password);//登錄 reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return success; } ftp.changeWorkingDirectory(path); ftp.storeFile(filename, input); input.close(); ftp.logout(); success = true; } catch (IOException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return success; }
兩個小例子: 1.將本地文件上傳到FTP伺服器上,代碼如下: @Test publicvoid testUpLoadFromDisk(){ try { FileInputStream in=new FileInputStream(new File("D:/test.txt")); boolean flag = uploadFile("127.0.0.1", 21, "test", "test", "D:/ftp", "test.txt", in); System.out.println(flag); } catch (FileNotFoundException e) { e.printStackTrace(); } }pre/pre @Test public void testUpLoadFromDisk(){ try { FileInputStream in=new FileInputStream(new File("D:/test.txt")); boolean flag = uploadFile("127.0.0.1", 21, "test", "test", "D:/ftp", "test.txt", in); System.out.println(flag); } catch (FileNotFoundException e) { e.printStackTrace(); } }
2.在FTP伺服器上生成一個文件,並將一個字元串寫入到該文件中 @Test publicvoid testUpLoadFromString(){ try { InputStream input = new ByteArrayInputStream("test ftp".getBytes("utf-8")); boolean flag = uploadFile("127.0.0.1", 21, "test", "test", "D:/ftp", "test.txt", input); System.out.println(flag); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }pre/pre @Test public void testUpLoadFromString(){ try { InputStream input = new ByteArrayInputStream("test ftp".getBytes("utf-8")); boolean flag = uploadFile("127.0.0.1", 21, "test", "test", "D:/ftp", "test.txt", input); System.out.println(flag); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }

『貳』 java如何實現將FTP文件轉移到另一個FTP伺服器上

你有FTPClient就比較好辦,假如你的兩台FTP伺服器分別為fs1和fs2

在本地開發代碼思路如下:

  1. 通過FTPClient連接上fs1,然後下載(可以循環批量下載)到本地伺服器,保存到一個臨時目錄。

  2. 下載完成後,FTPClient斷開與fs1的連接,記得必須logout。

  3. 本地伺服器通過FileInputStream將剛下載到臨時目錄的文件讀進來,得到一個List<File>集合。

  4. 通過FTPClient連接上fs2,循環List<File>集合,將文件上傳至fs2的特定目錄,然後清空臨時目錄,上傳完畢後,斷開fs2的連接,同樣必須logout。

『叄』 java 實現ftp上傳如何創建文件夾

這個功能我也剛寫完,不過我也是得益於同行,現在我也把自己的分享給大家,希望能對大家有所幫助,因為自己的項目不涉及到創建文件夾,也僅作分享,不喜勿噴謝謝!

interface:
packagecom.sunline.bank.ftputil;

importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importorg.apache.commons.net.ftp.FTPClient;

publicinterfaceIFtpUtils{
/**
*ftp登錄
*@paramhostname主機名
*@paramport埠號
*@paramusername用戶名
*@parampassword密碼
*@return
*/
publicFTPClientloginFtp(Stringhostname,Integerport,Stringusername,Stringpassword);
/**
*上穿文件
*@paramhostname主機名
*@paramport埠號
*@paramusername用戶名
*@parampassword密碼
*@paramfpathftp路徑
*@paramlocalpath本地路徑
*@paramfileName文件名
*@return
*/
(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName);
/**
*批量下載文件
*@paramhostname
*@paramport
*@paramusername
*@parampassword
*@paramfpath
*@paramlocalpath
*@paramfileName源文件名
*@paramfilenames需要修改成的文件名
*@return
*/
publicbooleandownloadFileList(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName,Stringfilenames);
/**
*修改文件名
*@paramlocalpath
*@paramfileName源文件名
*@paramfilenames需要修改的文件名
*/
(Stringlocalpath,StringfileName,Stringfilenames);
/**
*關閉流連接、ftp連接
*@paramftpClient
*@parambufferRead
*@parambuffer
*/
publicvoidcloseFtpConnection(FTPClientftpClient,,BufferedInputStreambuffer);
}

impl:
packagecom.sunline.bank.ftputil;

importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;
importorg.apache.commons.net.ftp.FTPClient;
importorg.apache.commons.net.ftp.FTPFile;
importorg.apache.commons.net.ftp.FTPReply;
importcommon.Logger;

{
privatestaticLoggerlog=Logger.getLogger(FtpUtilsImpl.class);
FTPClientftpClient=null;
Integerreply=null;

@Override
publicFTPClientloginFtp(Stringhostname,Integerport,Stringusername,Stringpassword){
ftpClient=newFTPClient();
try{
ftpClient.connect(hostname,port);
ftpClient.login(username,password);
ftpClient.setControlEncoding("utf-8");
reply=ftpClient.getReplyCode();
ftpClient.setDataTimeout(60000);
ftpClient.setConnectTimeout(60000);
//設置文件類型為二進制(避免解壓縮文件失敗)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//開通數據埠傳輸數據,避免阻塞
ftpClient.enterLocalActiveMode();
if(!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
log.error("連接FTP失敗,用戶名或密碼錯誤");
}else{
log.info("FTP連接成功");
}
}catch(Exceptione){
if(!FTPReply.isPositiveCompletion(reply)){
try{
ftpClient.disconnect();
}catch(IOExceptione1){
log.error("登錄FTP失敗,請檢查FTP相關配置信息是否正確",e1);
}
}
}
returnftpClient;
}

@Override
@SuppressWarnings("resource")
(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName){
booleanflag=false;
ftpClient=loginFtp(hostname,port,username,password);
BufferedInputStreambuffer=null;
try{
buffer=newBufferedInputStream(newFileInputStream(localpath+fileName));
ftpClient.changeWorkingDirectory(fpath);
fileName=newString(fileName.getBytes("utf-8"),ftpClient.DEFAULT_CONTROL_ENCODING);
if(!ftpClient.storeFile(fileName,buffer)){
log.error("上傳失敗");
returnflag;
}
buffer.close();
ftpClient.logout();
flag=true;
returnflag;
}catch(Exceptione){
e.printStackTrace();
}finally{
closeFtpConnection(ftpClient,null,buffer);
log.info("文件上傳成功");
}
returnfalse;
}

@Override
publicbooleandownloadFileList(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName,Stringfilenames){
ftpClient=loginFtp(hostname,port,username,password);
booleanflag=false;
=null;
if(fpath.startsWith("/")&&fpath.endsWith("/")){
try{
//切換到當前目錄
this.ftpClient.changeWorkingDirectory(fpath);
this.ftpClient.enterLocalActiveMode();
FTPFile[]ftpFiles=this.ftpClient.listFiles();
for(FTPFilefiles:ftpFiles){
if(files.isFile()){
System.out.println("=================="+files.getName());
FilelocalFile=newFile(localpath+"/"+files.getName());
bufferRead=newBufferedOutputStream(newFileOutputStream(localFile));
ftpClient.retrieveFile(files.getName(),bufferRead);
bufferRead.flush();
}
}
ftpClient.logout();
flag=true;

}catch(IOExceptione){
e.printStackTrace();
}finally{
closeFtpConnection(ftpClient,bufferRead,null);
log.info("文件下載成功");
}
}
modifiedLocalFileName(localpath,fileName,filenames);
returnflag;
}

@Override
(Stringlocalpath,StringfileName,Stringfilenames){
Filefile=newFile(localpath);
File[]fileList=file.listFiles();
if(file.exists()){
if(null==fileList||fileList.length==0){
log.error("文件夾是空的");
}else{
for(Filedata:fileList){
Stringorprefix=data.getName().substring(0,data.getName().lastIndexOf("."));
Stringprefix=fileName.substring(0,fileName.lastIndexOf("."));
System.out.println("index==="+orprefix+"prefix==="+prefix);
if(orprefix.contains(prefix)){
booleanf=data.renameTo(newFile(localpath+"/"+filenames));
System.out.println("f============="+f);
}else{
log.error("需要重命名的文件不存在,請檢查。。。");
}
}
}
}
}


@Override
publicvoidcloseFtpConnection(FTPClientftpClient,,BufferedInputStreambuffer){
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(null!=bufferRead){
try{
bufferRead.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(null!=buffer){
try{
buffer.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}


publicstaticvoidmain(String[]args)throwsIOException{
Stringhostname="xx.xxx.x.xxx";
Integerport=21;
Stringusername="edwftp";
Stringpassword="edwftp";
Stringfpath="/etl/etldata/back/";
StringlocalPath="C:/Users/Administrator/Desktop/ftp下載/";
StringfileName="test.txt";
Stringfilenames="ok.txt";
FtpUtilsImplftp=newFtpUtilsImpl();
/*ftp.modifiedLocalFileName(localPath,fileName,filenames);*/
ftp.downloadFileList(hostname,port,username,password,fpath,localPath,fileName,filenames);
/*ftp.uploadLocalFilesToFtp(hostname,port,username,password,fpath,localPath,fileName);*/
/*ftp.modifiedLocalFileName(localPath);*/
}
}

『肆』 公司要求做一個java和jsp怎麼實現ftp上傳的功能模塊,我沒有做過,誰有講得細一點的文章或網站。

form表單提交文件,建議用smartupload上傳,暫存在web伺服器目錄下,然後稍微一下下面的代碼,ftp上傳後,刪除暫存文件,ok
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.util.StringTokenizer;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

/**
* Ftp 服務類,對Apache的commons.net.ftp進行了包裝<br>
* 依賴庫文件:commons-net-1.4.1.jar
*
* @version 1.0 2008-02-18
* @author huchao@jbsoft
*/
public class FtpService {

public FtpService(String serverAddr, String lsenport, String userName,
String pswd) {
this.ftpServerAddress = serverAddr;
this.port = Integer.parseInt(lsenport);
this.user = userName;
this.password = pswd;
}

/**
* FTP 伺服器地址
*/
private String ftpServerAddress = null;
/**
* FTP 服務埠
*/
private int port = 21;
/**
* FTP 用戶名
*/
private String user = null;
/**
* FTP 密碼
*/
private String password = null;
/**
* FTP 數據傳輸超時時間
*/
private int timeout = 0;
/**
* 異常:登錄失敗
*/
private final I2HFException EXCEPTION_LOGIN = new I2HFException("COR101",
"FTP伺服器登錄失敗");
/**
* 異常:文件傳輸失敗
*/
private final I2HFException EXCEPTION_FILE_TRANSFER = new I2HFException(
"COR010", "FTP文件傳輸失敗");
/**
* 異常:IO異常
*/
private final I2HFException EXCEPTION_GENERAL = new I2HFException("COR010",
"FTP IO 異常");
private static final Logger logger = Logger.getLogger(FtpService.class);

/**
* 初始化FTP連接,並進行用戶登錄
*
* @return FTPClient
* @throws I2HFException
*/
public FTPClient initConnection() throws I2HFException {
FTPClient ftp = new FTPClient();
try {
// 連接到FTP
ftp.connect(ftpServerAddress, port);
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
throw new I2HFException("COR010", "FTP伺服器連接失敗");
}
// 登錄
if (!ftp.login(user, password)) {
throw EXCEPTION_LOGIN;
}
// 傳輸模式使用passive
ftp.enterLocalPassiveMode();
// 設置數據傳輸超時時間
ftp.setDataTimeout(timeout);
logger.info("FTP伺服器[" + ftpServerAddress + " : " + port + "]登錄成功");
} catch (I2HFException te) {
logger.info(te.errorMessage, te);
throw te;
} catch (IOException ioe) {
logger.info(ioe.getMessage(), ioe);
throw EXCEPTION_LOGIN;
}
return ftp;
}

/**
* 設置傳輸方式
*
* @param ftp
* @param binaryFile
* true:二進制/false:ASCII
* @throws I2HFException
*/
public void setTransferMode(FTPClient ftp, boolean binaryFile)
throws I2HFException {
try {
if (binaryFile) {
ftp.setFileType(FTP.BINARY_FILE_TYPE);
logger.info("FTP文件傳輸方式為:二進制");
} else {
ftp.setFileType(FTP.ASCII_FILE_TYPE);
logger.info("FTP文件傳輸方式為:ASCII");
}
} catch (IOException ex) {
logger.info(ex.getMessage(), ex);
throw EXCEPTION_GENERAL;
}
}

/**
* 在當前工作目錄下建立多級目錄結構
*
* @param ftp
* @param dir
* @throws I2HFException
*/
public void makeMultiDirectory(FTPClient ftp, String dir)
throws I2HFException {
try {
StringBuffer fullDirectory = new StringBuffer();
StringTokenizer toke = new StringTokenizer(dir, "/");
while (toke.hasMoreElements()) {
String currentDirectory = (String) toke.nextElement();
fullDirectory.append(currentDirectory);
ftp.makeDirectory(fullDirectory.toString());
if (toke.hasMoreElements()) {
fullDirectory.append('/');
}
}
} catch (IOException ex) {
logger.info(ex.getMessage(), ex);
throw EXCEPTION_GENERAL;
}
}

/**
* 更改伺服器當前路徑
*
* @param ftp
* @param dir
* @throws I2HFException
*/
public void changeWorkingDirectory(FTPClient ftp, String dir)
throws I2HFException {
try {
if (!ftp.changeWorkingDirectory(dir)) {
throw new I2HFException("COR010", "目錄[ " + dir + "]進入失敗");
}
} catch (I2HFException tfe) {
logger.info(tfe.errorMessage, tfe);
throw tfe;
} catch (IOException ioe) {
logger.info(ioe.getMessage(), ioe);
throw EXCEPTION_GENERAL;
}
}

/**
* 上傳文件到FTP伺服器
*
* @param ftp
* @param localFilePathName
* @param remoteFilePathName
* @throws I2HFException
*/
public void uploadFile(FTPClient ftp, String localFilePathName,
String remoteFilePathName) throws I2HFException {
InputStream input = null;
try {
input = new FileInputStream(localFilePathName);
boolean result = ftp.storeFile(remoteFilePathName, input);
if (!result) {
// 文件上傳失敗
throw EXCEPTION_FILE_TRANSFER;
}
logger.info("文件成功上傳到FTP伺服器");
} catch (I2HFException tfe) {
logger.info(tfe.getMessage(), tfe);
throw tfe;
} catch (IOException ioe) {
logger.info(ioe.getMessage(), ioe);
throw EXCEPTION_FILE_TRANSFER;
} finally {
try {
if (input != null) {
input.close();
}
} catch (IOException ex) {
logger.info("FTP對象關閉異常", ex);
}
}
}

/**
* 下載文件到本地
*
* @param ftp
* @param remoteFilePathName
* @param localFilePathName
* @throws I2HFException
*/
public void downloadFile(FTPClient ftp, String remoteFilePathName,
String localFilePathName) throws I2HFException {
boolean downloadResult = false;
OutputStream output = null;
try {
output = new FileOutputStream(localFilePathName);
downloadResult = ftp.retrieveFile(remoteFilePathName, output);
if (!downloadResult) {
// 如果是文件不存在將異常拋出
throw new I2HFException("COR011", "文件不存在");
}
logger.info("文件成功從FTP伺服器下載");
} catch (I2HFException tfe) {
logger.error(tfe.getMessage(), tfe);
throw tfe;
} catch (IOException ex) {
logger.error(ex.getMessage(), ex);
throw EXCEPTION_FILE_TRANSFER;
} finally {
try {
if (output != null) {
output.close();
}
if (!downloadResult) {
new File(localFilePathName).delete();
}
} catch (IOException ex) {
logger.error("FTP對象關閉異常", ex);
}
}
}

/**
* Method setFtpServerAddress.
*
* @param ftpServerAddress
* String
*/
public void setFtpServerAddress(String ftpServerAddress) {
this.ftpServerAddress = ftpServerAddress;
}

/**
* Method setUser.
*
* @param user
* String
*/
public void setUser(String user) {
this.user = user;
}

/**
* Method setPassword.
*
* @param password
* String
*/
public void setPassword(String password) {
this.password = password;
}

/**
* Method setTimeout.
*
* @param timeout
* String
*/
public void setTimeout(String timeout) {
try {
this.timeout = Integer.parseInt(timeout);
} catch (NumberFormatException ex) {
// 默認超時時間500毫秒
this.timeout = 500;
}
}

/**
* Method setPort.
*
* @param port
* String
*/
public void setPort(String port) {
try {
this.port = Integer.parseInt(port);
} catch (NumberFormatException ex) {
// 默認埠21
this.port = 21;
}
}
}
=====================================
jsp上傳部分
===================================
<form method="post" name="uploadform" id="uploadform" action="upload" ENCTYPE="multipart/form-data">

<input type="hidden" name="service" value="com.jbsoft.i2hf.corpor.services.CstBatchBizServices.exclUpload"/>
<table cellspacing="0" cellpadding="0">
<tr>
<td width="20%" align="right">上傳本地文件:</td>
<td width="80%"><input class="" style="width:300px" type="file" width="300px" name="exclname" id="exclname"/></td>
</tr>
</table>
</form>
============================================
上傳的servlet用的是smartupload
,部分代碼可以參考一下:
==========================================
SmartUpload su = new SmartUpload();
su.setCharset("UTF-8");
su.initialize(getServletConfig(), request, response);
su.setMaxFileSize(10240000);
su.setTotalMaxFileSize(102400000);
su.setAllowedFilesList("xls");
su.upload();
===========================================
代碼裡面有一些客戶的信息,不能全部給你哈

熱點內容
lol伺服器人數怎麼擠 發布:2025-03-19 01:29:19 瀏覽:838
兄弟連的php 發布:2025-03-19 01:24:25 瀏覽:810
自己做腳本可不可以 發布:2025-03-19 01:20:13 瀏覽:533
33的源碼值 發布:2025-03-19 01:13:25 瀏覽:814
虛榮安卓怎麼充值 發布:2025-03-19 01:12:27 瀏覽:892
如何更改報考密碼 發布:2025-03-19 01:08:12 瀏覽:416
python日期類型 發布:2025-03-19 01:02:28 瀏覽:415
android飛機大戰源碼 發布:2025-03-19 00:56:52 瀏覽:736
javaset方法 發布:2025-03-19 00:44:21 瀏覽:246
淘寶上傳文件夾 發布:2025-03-19 00:36:30 瀏覽:73