java使用FTP上传文件

硅谷探秘者 2447 0 0

pom依赖

<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>3.6</version>
</dependency>


FTP服务类

package club.jiajiajia.bulider.service;

import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;

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.FTPReply;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
/**
 * ftp服务
 * @author JIA_JIAJIA
 * @website http://www.jiajiajia.club
 * @da2019年6月3日
 *
 */
@Service
public class FTPServer {
	@Value("${ftp.ip}")
	private String ip;
	
	@Value("${ftp.port}")
	private Integer port;
	
	@Value("${ftp.username}")
	private String username;
	
	@Value("${ftp.password}")
	private String password;
	
	public boolean uploadFile( String basePath,
			String filePath, String filename, InputStream input) {
			FTPClient ftp= new FTPClient();
			try {
				ftp.connect(ip, port);// 连接FTP服务器
				ftp.login(username, password);// 登录
			} catch (SocketException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			boolean result = false;
			try {
				int reply;
			
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return result;
			}
			//切换到上传目录
			if (!ftp.changeWorkingDirectory(basePath+filePath)) {
				//如果目录不存在创建目录
				String[] dirs = filePath.split("/");
				String tempPath = basePath;
				for (String dir : dirs) {
					if (null == dir || "".equals(dir)) continue;
					tempPath += "/" + dir;
					if (!ftp.changeWorkingDirectory(tempPath)) {
						if (!ftp.makeDirectory(tempPath)) {
							return result;
						} else {
							ftp.changeWorkingDirectory(tempPath);
						}
					}
				}
			}
			ftp.setControlEncoding("ISO-8859-1");//设置编码集为GBK支持中文
			FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
			conf.setServerLanguageCode("zh");
			ftp.configure(conf);
			//设置上传文件的类型为二进制类型
			ftp.setFileType(FTP.BINARY_FILE_TYPE);
			ftp.enterLocalPassiveMode();// 设为被动模式
			filename= new String(filename.getBytes("GBK"),"ISO-8859-1");
			String [] strs = ftp.listNames();
			boolean b = true;
			for (String str : strs){
				if(str != null && str.equals(filename)){
				b = false;
				break;
				}
			}
			if(b){
				if (!ftp.storeFile(filename, input)) {
						return result;
					}
				}
				input.close();
				result = true;
				ftp.logout();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (ftp.isConnected()) {
					try {
						ftp.logout();
						ftp.disconnect();
					} catch (IOException e) {
					}
				}
			}
			return result;
		}
	
	public boolean deleteFile(String pathname,String filename) {
		FTPClient ftp= new FTPClient();
		try {
			ftp.connect(ip, port);// 连接FTP服务器
			ftp.login(username, password);// 登录
		} catch (SocketException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		boolean flag = false;
		try {
			int replyCode = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(replyCode)) {
				return flag;
			}
			// 切换FTP目录
			ftp.changeWorkingDirectory(pathname);
			ftp.dele(filename);
			flag = true;
			ftp.logout();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.logout();
					ftp.disconnect();
				} catch (IOException e) {
				}
			}
		}
		return flag;
	}
}


项目使用springboot框架,一些信息都是从配置文件中。

	@Value("${ftp.ip}")
	private String ip;
	
	@Value("${ftp.port}")
	private Integer port;
	
	@Value("${ftp.username}")
	private String username;
	
	@Value("${ftp.password}")
	private String password;

分别是 ip地址,端口号,用户名,密码。


评论区
请写下您的评论...
暂无评论...
猜你喜欢
minio 2269 创建buckets 创建serviceaccounts java maven依赖: dependency groupIdio.minio/groupId
工具 1920 服务端(接受) /** *接口 *@paramtype *@return */ @RequestMapping(value="/upFile",method
前端(h5) 2748 后端这么写packagecn.com.dzqc.controller;importjavax.servlet.http.HttpServletRequest;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;importorg.sp
框架 2025 springboot与回显资源映射路径配置:packagecom.dzqc.yx.controller
框架 7723 一次实现的进度条原理:在之前,请求以下服务器,获取一个socketId(作来标识本次连接,服务器端也是通过这个id找到对应的连接,然后给这个连接发送消息(进度)),此时socket
weblog 2445 java使easypoi导出并下载excel简单导出测试如图:一、pomdependencygroupIdcn.afterturn/groupIdartifactIdeasypoi
框架 2759 $FileSizeLimitExceededException:Thefieldfileexceedsitsmaximumpermittedsizeof1048576bytes.yml加配置springboot2.0配置spring:servlet:multipart:max-file-s
工具 3025 引入pomdependencygroupIdorg.dom4j/groupIdartifactIddom4j/artifactIdversion2.0.0/version/dependency需
归档
2018-11  12 2018-12  33 2019-01  28 2019-02  28 2019-03  32 2019-04  27 2019-05  33 2019-06  6 2019-07  12 2019-08  12 2019-09  21 2019-10  8 2019-11  15 2019-12  25 2020-01  9 2020-02  5 2020-03  16 2020-04  4 2020-06  1 2020-07  7 2020-08  13 2020-09  9 2020-10  5 2020-12  3 2021-01  1 2021-02  5 2021-03  7 2021-04  4 2021-05  4 2021-06  1 2021-07  7 2021-08  2 2021-09  8 2021-10  9 2021-11  16 2021-12  14 2022-01  7 2022-05  1 2022-08  3 2022-09  2 2022-10  2 2022-12  5 2023-01  3 2023-02  1 2023-03  4 2023-04  2 2023-06  3 2023-07  4 2023-08  1 2023-10  1 2024-02  1 2024-03  1 2024-04  1
标签
算法基础 linux 前端 c++ 数据结构 框架 数据库 计算机基础 储备知识 java基础 ASM 其他 深入理解java虚拟机 nginx git 消息中间件 搜索 maven redis docker dubbo vue 导入导出 软件使用 idea插件 协议 无聊的知识 jenkins springboot mqtt协议 keepalived minio mysql ensp 网络基础 xxl-job rabbitmq haproxy srs 音视频 webrtc javascript
目录
没有一个冬天不可逾越,没有一个春天不会来临。最慢的步伐不是跬步,而是徘徊,最快的脚步不是冲刺,而是坚持。