当前位置:首页 » 文件管理 » 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