Commit c6cebdb2 by ypenglv

FTP

1 parent ed7ce71d
package org.nafmii.app; package org.nafmii.app;
import org.mybatis.spring.annotation.MapperScan; import org.mybatis.spring.annotation.MapperScan;
import org.nafmii.common.ftp.EnableFtpServer;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
...@@ -10,6 +11,7 @@ import org.springframework.cloud.openfeign.EnableFeignClients; ...@@ -10,6 +11,7 @@ import org.springframework.cloud.openfeign.EnableFeignClients;
@EnableEurekaClient @EnableEurekaClient
@EnableFeignClients @EnableFeignClients
@MapperScan("org.nafmii.app/**/dao") @MapperScan("org.nafmii.app/**/dao")
@EnableFtpServer
public class NafmiiAppApplication { public class NafmiiAppApplication {
public static void main(String[] args) { public static void main(String[] args) {
......
package org.nafmii.app.user.controller;
import org.nafmii.app.user.param.LoginParam;
import org.nafmii.common.response.ApiResponse;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author lvyp
* @date 2021/5/11
*/
@FeignClient("nafmii-app")
@RequestMapping(value = "")
public interface TestClinet {
@PostMapping("/login")
@ResponseBody
public ApiResponse login(@RequestBody LoginParam loginParam);
}
package org.nafmii.app.user.controller; package org.nafmii.app.user.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import org.nafmii.app.user.dto.LoginDto; import org.nafmii.app.user.dto.LoginDto;
...@@ -8,13 +10,17 @@ import org.nafmii.app.user.param.LoginParam; ...@@ -8,13 +10,17 @@ import org.nafmii.app.user.param.LoginParam;
import org.nafmii.app.user.param.RegisterParam; import org.nafmii.app.user.param.RegisterParam;
import org.nafmii.app.user.service.UserService; import org.nafmii.app.user.service.UserService;
import org.nafmii.app.user.vo.UserVO; import org.nafmii.app.user.vo.UserVO;
import org.nafmii.common.ftp.FTPClientHelper;
import org.nafmii.common.response.ApiResponse; import org.nafmii.common.response.ApiResponse;
import org.nafmii.common.utils.BeanTransferUtils;
import org.nafmii.common.utils.RequestUtils; import org.nafmii.common.utils.RequestUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import sun.net.ftp.FtpClient;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.io.File;
/** /**
* @author:zhoujh * @author:zhoujh
...@@ -27,10 +33,12 @@ import javax.annotation.Resource; ...@@ -27,10 +33,12 @@ import javax.annotation.Resource;
@RestController @RestController
@RequestMapping("/app/nafmii/user") @RequestMapping("/app/nafmii/user")
@Api(tags = "2.0.1", description = "用户登陆注册操作操作【zjh】") @Api(tags = "2.0.1", description = "用户登陆注册操作操作【zjh】")
public class UserController { public class UserController {
@Resource @Resource
private UserService userService; private UserService userService;
@Resource
private TestClinet testClinet;
@ApiOperation( value = "模拟用户登陆",notes = "模拟用户登陆") @ApiOperation( value = "模拟用户登陆",notes = "模拟用户登陆")
@PostMapping("/loginTest") @PostMapping("/loginTest")
@ResponseBody @ResponseBody
...@@ -54,6 +62,24 @@ public class UserController { ...@@ -54,6 +62,24 @@ public class UserController {
ApiResponse<UserVO> login = userService.userLogin(loginParam); ApiResponse<UserVO> login = userService.userLogin(loginParam);
return login; return login;
} }
@ApiOperation( value = "app用户登陆接口(密码加验证码)",notes = "app用户登陆接口(密码加验证码)")
@PostMapping("/testFtp")
@ResponseBody
public ApiResponse testFtp (){
String ftpClient = FTPClientHelper.uploadFile("1",new File("e:/new1.txt"),"aa");
System.out.println(ftpClient);
return new ApiResponse();
}
@ApiOperation( value = "app用户登陆接口(密码加验证码)",notes = "app用户登陆接口(密码加验证码)")
@PostMapping("/yyy")
@ResponseBody
public ApiResponse yyy (@RequestBody JSONObject object){
LoginParam loginParam = BeanTransferUtils.transfer(object,LoginParam.class);
if("001".equals(object.get("apiCode"))){
testClinet.login(loginParam);
}
return new ApiResponse();
}
} }
...@@ -27,16 +27,16 @@ spring: ...@@ -27,16 +27,16 @@ spring:
pool-name: NFMII_HikariCP pool-name: NFMII_HikariCP
connection-test-query: SELECT 1 connection-test-query: SELECT 1
redis: redis:
# Redis数据库索引(默认为0) # Redis数据库索引(默认为0)
database: 0 database: 0
# Redis服务器地址 # Redis服务器地址
host: 127.0.0.1 host: 127.0.0.1
port: 6379 port: 6379
# Redis服务器连接密码(默认为空) # Redis服务器连接密码(默认为空)
password: password:
jedis: jedis:
pool: pool:
# 连接池最大连接数(使用负值表示没有限制) # 连接池最大连接数(使用负值表示没有限制)
max-active: 20 max-active: 20
max-wait: -1ms max-wait: -1ms
max-idle: 10 max-idle: 10
...@@ -50,7 +50,12 @@ spring: ...@@ -50,7 +50,12 @@ spring:
client: client:
enabled: true enabled: true
sampler: sampler:
probability: 1.0 #zipkin采集率 0.1表示 10%采集率 probability: 1.0 #zipkin采集率 0.1表示 10%采集率
nafmii: nafmii:
log-path: D:/NAFMII log-path: D:/NAFMII
dao-uri: org.nafmii.app
\ No newline at end of file \ No newline at end of file
dao-uri: org.nafmii.app
ftp:
host: 127.0.0.1
password: peng1003
prot: 21
username: ypenglv
\ No newline at end of file \ No newline at end of file
...@@ -18,6 +18,7 @@ ...@@ -18,6 +18,7 @@
<fastjson.version>1.2.58</fastjson.version> <fastjson.version>1.2.58</fastjson.version>
<ojdbc.version>10.2.0.4</ojdbc.version> <ojdbc.version>10.2.0.4</ojdbc.version>
<jjwt.version>0.9.1</jjwt.version> <jjwt.version>0.9.1</jjwt.version>
<jasypt.version>3.0.2</jasypt.version>
</properties> </properties>
<dependencies> <dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign --> <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign -->
...@@ -215,7 +216,28 @@ ...@@ -215,7 +216,28 @@
<artifactId>HikariCP</artifactId> <artifactId>HikariCP</artifactId>
<version>4.0.0</version> <version>4.0.0</version>
</dependency> </dependency>
<!-- ftp -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
<!-- jasypt -->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>${jasypt.version}</version>
</dependency>
<!-- 线程池-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
package org.nafmii.common.config;
import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.StandardPBEByteEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
import org.jasypt.exceptions.EncryptionOperationNotPossibleException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author by zhangbr
* @date 2020/7/25
*/
@Configuration
public class EncryptConfig {
private final static String ENCRYPT_PASSWORD = "P0O9I8U7Y6T5R4E3W2Q1";
private static StringEncryptor encrypt = initStringEncrypt();
@Bean("jasyptStringEncryptor")
public StringEncryptor stringEncryptor() {
return encrypt;
}
private static StringEncryptor initStringEncrypt(){
PooledPBEStringEncryptor encrypt = new PooledPBEStringEncryptor();
SimpleStringPBEConfig config = new SimpleStringPBEConfig();
config.setPassword(ENCRYPT_PASSWORD);
config.setAlgorithm(StandardPBEByteEncryptor.DEFAULT_ALGORITHM);
config.setKeyObtentionIterations("1000");
config.setPoolSize("1");
config.setProviderName("SunJCE");
config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
config.setStringOutputType("base64");
encrypt.setConfig(config);
return encrypt;
}
/**
* 加密
* @param code 编码
* @return String
*/
public static String encrypt(String code){
return encrypt.encrypt(code);
}
/**
* 解密
* @param code 编码
* @return String
*/
public static String decrypt(String code) throws EncryptionOperationNotPossibleException {
return encrypt.decrypt(code);
}
}
package org.nafmii.common.ftp;
import org.springframework.context.annotation.Import;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author by zhangbr
* @date 2020/7/24.
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({FTPClientConfigure.class, FTPClientHelper.class})
public @interface EnableFtpServer {
}
package org.nafmii.common.ftp;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* @author by zhangbr
* @date 2020/7/24.
*/
@EqualsAndHashCode(callSuper = true)
@Data
@ConfigurationProperties("nafmii.ftp")
class FTPClientConfigure extends GenericObjectPoolConfig<FTPClient> {
/**
* ftp服务器地址
*/
private String host;
/**
* ftp登录账号
*/
private String username;
/**
* ftp登录密码
*/
private String password;
/**
* ftp服务器端口号,默认为21
*/
private Integer port = 21;
/**
* 上传附件前缀
*/
private String prefix;
/**
* ftp连接超时时间,毫秒,0 = 无限超时
*/
private int connectTimeOut = 0;
/**
* 缓冲区大小
*/
private int bufferSize = 1024;
/**
* 传输文件类型
*/
private int transferFileType = FTPClient.BINARY_FILE_TYPE;
/**
* 编码格式
*/
private String controlEncoding = "utf-8";
/**
* 默认120S
*/
private int dataTimeout = 120 * 1000;
/**
* 是否启用被动模式
*/
private boolean passiveMode = true;
/**
* 开启线程数
*/
private int threadNum = 8;
/**
* 是否上传文件重命名;
*/
private boolean renameUploaded = false;
/**
* 重试次数
*/
private int retryTimes = 3;
private boolean ipv4 = false;
}
package org.nafmii.common.ftp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.nafmii.common.exception.BusinessException;
import javax.annotation.Resource;
import java.io.IOException;
/**
* FTPClient工厂类,通过FTPClient工厂提供FTPClient实例的创建和销毁
* @author by zhangbr
* @date 2020/7/24.
*/
@Slf4j
public class FTPClientFactory{
private FTPClientConfigure config;
public FTPClientFactory(FTPClientConfigure config){
this.config = config;
}
/**
* 新建对象
*/
public FTPClient create() {
FTPClient ftpClient = new FTPClient();
ftpClient.setConnectTimeout(config.getConnectTimeOut());
try {
log.info("======连接ftp服务器:" + config.getHost() + ":" + config.getPort() + "======");
ftpClient.connect(config.getHost(), config.getPort());
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
log.info("======FTPServer连接被拒绝======");
return null;
}
boolean result = ftpClient.login(config.getUsername(), config.getPassword());
if (!result) {
throw new BusinessException(-100, "ftpClient登陆失败");
}
ftpClient.setControlEncoding(config.getControlEncoding());
ftpClient.setBufferSize(config.getBufferSize());
ftpClient.setFileType(config.getTransferFileType());
ftpClient.setDataTimeout(config.getDataTimeout());
ftpClient.setUseEPSVwithIPv4(config.isIpv4());
if (config.isPassiveMode()) {
ftpClient.enterLocalPassiveMode();
}
} catch (IOException e) {
log.info("FTP连接失败:", e.getMessage());
throw new BusinessException(-100, "FTP服务器连接失败");
}
return ftpClient;
}
}
\ No newline at end of file \ No newline at end of file
package org.nafmii.common.ftp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.nafmii.common.constant.MessageEnum;
import org.nafmii.common.exception.BusinessException;
import org.nafmii.common.utils.RequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/**
* @author by zhangbr
* @date 2020/7/24.
*/
@Slf4j
public class FTPClientHelper implements AutoCloseable {
@Resource
private FTPClientConfigure configure;
private static FTPClientHelper ftpClientHelper;
private static FTPClientFactory factory;
private static final String SUB_SPOT = ".";
/**
* 初始化设置
*/
@PostConstruct
public boolean init() {
factory = new FTPClientFactory(configure);
ftpClientHelper = this;
return true;
}
/**
* 获取一个连接对象
* @return FTPClient
*/
private static FTPClient getClient() {
return factory.create();
}
/**
* 列出目录下的所有文件
* @param pathName 路径
* @return FTPFile[]
*/
public static FTPFile[] listFiles(String pathName) {
FTPClient client = getClient();
try {
return client.listFiles(pathName);
} catch (IOException e) {
log.info(e.getMessage());
}finally {
releaseClient(client);
}
return null;
}
/**
* 下载 remote文件流
* @param form ftp资源下载
* @return boolean
*/
public static boolean retrieveFile(FileDownLoadForm form) {
String remote = form.encodeFileId();
if (StringUtils.isEmpty(remote)){
log.info("==============下载FTP文件失败:remote:{}=============", remote, remote);
throw new BusinessException(MessageEnum.FILE_DOWN_FAIL.getCode(), MessageEnum.FILE_DOWN_FAIL.getRemarks());
}
log.info("==============开始下载FTP文件:{}=============", remote);
long startTime = System.currentTimeMillis();
FTPClient client = getClient();
OutputStream outputStream = null;
try {
if (!existFile(client, remote)){
log.info("==============下载FTP文件失败:未找到文件:{}=============", remote);
throw new BusinessException(MessageEnum.FILE_DOWN_FAIL.getCode(), MessageEnum.FILE_DOWN_FAIL.getRemarks());
}
outputStream = RequestUtils.getResponse().getOutputStream();
boolean result = client.retrieveFile(remote, outputStream);
long endTime = System.currentTimeMillis();
log.info("==============下载FTP文件:{}完成,result:{},用时:{}=============", remote, result, (endTime - startTime) + "ms");
return result;
} catch (IOException e) {
log.info(e.getMessage());
throw new BusinessException(MessageEnum.FILE_DOWN_FAIL.getCode(), MessageEnum.FILE_DOWN_FAIL.getRemarks());
} finally {
if (outputStream != null){
try {
outputStream.close();
} catch (IOException e) {
log.info(e.getMessage());
}
}
releaseClient(client);
}
}
/**
* 下载 remote文件流
* @param remote ftp资源文件路径
* @return byte[]
*/
public static InputStream retrieveFileStream(String remote) {
log.info("==============开始下载FTP文件:{}=============", remote);
long startTime = System.currentTimeMillis();
FTPClient client = getClient();
InputStream in = null;
try {
if (!existFile(client, remote)){
log.info("==============下载FTP文件失败:未找到文件:{}=============", remote);
throw new BusinessException(MessageEnum.FILE_DOWN_FAIL.getCode(), MessageEnum.FILE_DOWN_FAIL.getRemarks());
}
in = client.retrieveFileStream(remote);
long endTime = System.currentTimeMillis();
log.info("==============下载FTP文件:{}完成,用时:{}=============", remote, (endTime - startTime) + "ms");
} catch (IOException e) {
log.info(e.getMessage());
} finally {
releaseClient(client);
}
return in;
}
/**
* 根据业务分类上传文件(同步上传)
* @param business 业务模块
* @param inputStream 文件流
* @return String
*/
public static String uploadFile(String business, InputStream inputStream, String fileName) {
String remotePath;
FTPClient client = getClient();
try {
remotePath = makeDirectory(client, business);
remotePath += fileName;
upload(client, remotePath, inputStream);
} catch (IOException e) {
throw new BusinessException(-102, "附件上传失败!");
} finally {
releaseClient(client);
}
return remotePath;
}
/**
* 根据业务分类上传文件(同步上传)
* @param business 业务模块
* @param file 文件资源
* @return String
*/
public static String uploadFile(String business, File file, String fileName) {
if (file == null || StringUtils.isEmpty(business) || StringUtils.isEmpty(fileName)){
log.info("======上传附件异常======business:{},fileName:{}", business, fileName);
throw new BusinessException(-101, "附件上传失败!");
}
String remotePath;
FTPClient client = getClient();
InputStream inputStream;
try {
remotePath = makeDirectory(client, business);
remotePath += fileName;
inputStream = new FileInputStream(file);
upload(client, remotePath, inputStream);
} catch (IOException e) {
throw new BusinessException(-102, "附件上传失败!");
} finally {
releaseClient(client);
}
return remotePath;
}
/**
* 根据路径上传文件(异步上传)
* @param filePathName ftp附件上传路径
* @param file 文件资源
* @return boolean
*/
public static boolean uploadFile(String filePathName, File file) {
if (file == null || StringUtils.isEmpty(filePathName)){
log.info("======上传附件异常======filePathName:{}", filePathName);
throw new BusinessException(-103, "附件上传失败!");
}
FTPClient client = getClient();
InputStream inputStream;
boolean flag;
try {
inputStream = new FileInputStream(file);
flag = upload(client, filePathName, inputStream);
} catch (IOException e) {
log.info(e.getMessage());
throw new BusinessException(-104, "附件上传失败!");
} finally {
releaseClient(client);
}
return flag;
}
/**
* 多文件上传
* @param business 业务模块
* @param files 文件集合
* @return List<FileVO>
*/
public static List<FileVO> uploadFiles(String business, MultipartFile[] files){
List<FileVO> fileList = new ArrayList<>();
FTPClient client = getClient();
try {
String remotePath = makeDirectory(client, business);
for (MultipartFile file : files) {
try {
//上传文件
String fileName = file.getOriginalFilename();
if (StringUtils.isEmpty(fileName)){
continue;
}
String suffix = fileName.substring(fileName.lastIndexOf(SUB_SPOT));
if (StringUtils.isEmpty(suffix)){
continue;
}
String newFileName = UUID.randomUUID().toString().replace("-", "") + suffix;
String remoteFilePath = remotePath + newFileName;
InputStream inputStream = file.getInputStream();
upload(client, remoteFilePath, inputStream);
inputStream.close();
fileList.add(new FileVO(remoteFilePath, newFileName));
} catch (IOException e) {
throw new BusinessException(MessageEnum.FILE_UPLOAD_FAIL.getCode(), MessageEnum.FILE_UPLOAD_FAIL.getRemarks());
}
}
} catch (IOException e) {
throw new BusinessException(-100, "FTP目录生成失败!");
} finally {
releaseClient(client);
}
return fileList;
}
private static boolean upload(FTPClient client, String filePathName, InputStream inputStream){
try {
log.info("==============FTP文件:{},开始上传=============", filePathName);
long start = System.currentTimeMillis();
boolean result = client.storeFile(filePathName, inputStream);
long end = System.currentTimeMillis();
log.info("==============FTP文件:{},上传完成时间:{}=============", filePathName, (end - start) + "ms");
return result;
} catch (IOException e) {
throw new BusinessException(MessageEnum.FILE_UPLOAD_FAIL.getCode(), MessageEnum.FILE_UPLOAD_FAIL.getRemarks());
}finally {
if (inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
log.info(e.getMessage());
}
}
}
}
/**
* 创建多层目录文件,如果有ftp服务器已存在该文件,则不创建,如果无,则创建
* @param business 业务模块
* @return String
*/
public static String makeDirectory(String business){
String remotePath;
FTPClient client = getClient();
try {
remotePath = makeDirectory(client, business);
} catch (IOException e) {
throw new BusinessException(-100, "文件目录生成失败!");
} finally {
releaseClient(client);
}
return remotePath;
}
/**
* 创建多层目录文件,如果有ftp服务器已存在该文件,则不创建,如果无,则创建
* @param client client
* @param business 业务模块
* @return String
* @throws IOException e
*/
private static String makeDirectory(FTPClient client, String business) throws IOException {
log.info("==============开始生成FTP目录:{}=============", business);
long startTime = System.currentTimeMillis();
String directory = getRemoteBusinessPath(business);
// 如果远程目录不存在,则递归创建远程服务器目录
if (!directory.equalsIgnoreCase(File.separator) && !changeWorkingDirectory(client, directory)) {
int start;
int end;
if (directory.startsWith(File.separator)) {
start = 1;
} else {
start = 0;
}
end = directory.indexOf(File.separator, start);
String path = "";
String paths = "";
while (true) {
String subDirectory = new String(directory.substring(start, end).getBytes("GBK"), StandardCharsets.ISO_8859_1);
path = path + File.separator + subDirectory;
if (!existFile(client, path)) {
if (createDirectory(client, subDirectory)) {
changeWorkingDirectory(client, subDirectory);
} else {
log.info("创建目录[" + subDirectory + "]失败");
changeWorkingDirectory(client, subDirectory);
}
} else {
changeWorkingDirectory(client, subDirectory);
}
paths = paths + File.separator + subDirectory;
start = end + 1;
end = directory.indexOf(File.separator, start);
// 检查所有目录是否创建完毕
if (end <= start) {
break;
}
}
}
long endTime = System.currentTimeMillis();
log.info("==============生成FTP目录:{}完成,用时:{}=============", business, (endTime - startTime) + "ms");
return directory;
}
/**
* 根据业务模块创建远程文件路径
* @param business 业务模块
* @return String
*/
public static String getRemoteBusinessPath(String business){
if (StringUtils.isEmpty(business)){
throw new BusinessException(-100, "业务模块不能为空!");
}
String filePath = StringUtils.isEmpty(ftpClientHelper.configure.getPrefix()) ? "" : ftpClientHelper.configure.getPrefix();
if (!filePath.startsWith(File.separator)){
filePath = File.separator + filePath;
}
if (!filePath.endsWith(File.separator)){
filePath += File.separator;
}
filePath += business + File.separator;
filePath += new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + File.separator;
return filePath;
}
/**
* 判断ftp服务器文件是否存在
* @param path path
* @return boolean
*/
public static boolean existFile(String path){
log.info("==============校验FTP文件是否存在:{}=============", path);
long startTime = System.currentTimeMillis();
boolean flag;
FTPClient client = getClient();
try {
flag = existFile(client, path);
} finally {
releaseClient(client);
}
long endTime = System.currentTimeMillis();
log.info("==============校验FTP文件:{}完成,结果:{},用时:{}=============", path, flag, (endTime - startTime) + "ms");
return flag;
}
/**
* 判断ftp服务器文件是否存在
* @param client client
* @param path path
* @return boolean
*/
private static boolean existFile(FTPClient client, String path){
boolean flag = false;
FTPFile[] ftpFileArr = new FTPFile[0];
try {
ftpFileArr = client.listFiles(path);
} catch (IOException e) {
log.info(e.getMessage());
}
if (ftpFileArr.length > 0) {
flag = true;
}
return flag;
}
/**
* 改变目录路径
* @param client client
* @param directory directory
* @return boolean
*/
private static boolean changeWorkingDirectory(FTPClient client, String directory) {
try {
return client.changeWorkingDirectory(directory);
} catch (IOException ioe) {
log.info(ioe.getMessage());
throw new BusinessException(-100, "改变目录路径异常!");
}
}
/**
* 创建目录 单个不可递归
* @param client client
* @param pathName ftp路径
* @return boolean
* @throws IOException e
*/
private static boolean createDirectory(FTPClient client, String pathName) throws IOException {
return client.makeDirectory(pathName);
}
/**
* 删除目录,单个不可递归
* @param pathName ftp路径
* @return boolean
* @throws Exception e
*/
public static boolean removeDirectory(String pathName) throws Exception {
FTPClient client = getClient();
try {
return client.removeDirectory(pathName);
} finally {
releaseClient(client);
}
}
/**
* 删除文件 单个 ,不可递归
* @param pathName ftp资源文件路径
* @return boolean
* @throws Exception e
*/
public static boolean deleteFile(String pathName) throws Exception {
FTPClient client = getClient();
try {
return client.deleteFile(pathName);
} finally {
releaseClient(client);
}
}
/**
* 释放连接
* @param client client
*/
private static void releaseClient(FTPClient client) {
if (client == null) {
return;
}
try {
client.logout();
client.disconnect();
} catch (Exception io) {
log.info(io.getMessage());
}
}
@Override
public void close() throws Exception {
// TODO Auto-generated method stub
log.info("---Resources Closed---.");
}
}
package org.nafmii.common.ftp;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.jasypt.exceptions.EncryptionOperationNotPossibleException;
import org.nafmii.common.config.EncryptConfig;
import org.nafmii.common.constant.MessageEnum;
import org.nafmii.common.exception.BusinessException;
import org.springframework.util.StringUtils;
import javax.validation.constraints.NotEmpty;
import java.io.File;
/**
* @author by zhangbr
* @date 2020/7/25
*/
@Slf4j
@Data
public class FileDownLoadForm {
@ApiModelProperty("附件ID")
@NotEmpty(message = "附件ID不能为空")
private String fileId;
public String encodeFileId() {
if (!StringUtils.isEmpty(fileId)){
try {
return EncryptConfig.decrypt(fileId);
} catch (EncryptionOperationNotPossibleException e) {
log.info("======文件ID解码失败======");
throw new BusinessException(MessageEnum.FILE_DOWN_FAIL.getCode(), MessageEnum.FILE_DOWN_FAIL.getRemarks());
}
}
return null;
}
public String encodeFileName(){
if (!StringUtils.isEmpty(fileId)){
try {
String filePath = EncryptConfig.decrypt(fileId);
if (!StringUtils.isEmpty(filePath)){
String fileName = filePath;
if (filePath.lastIndexOf(File.separator) >= 0){
fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1);
}
return fileName;
}
} catch (EncryptionOperationNotPossibleException e) {
log.info("======文件名称解码失败======");
throw new BusinessException(MessageEnum.FILE_DOWN_FAIL.getCode(), MessageEnum.FILE_DOWN_FAIL.getRemarks());
}
}
return null;
}
}
package org.nafmii.common.ftp;
import io.swagger.annotations.ApiModelProperty;
import org.nafmii.common.config.EncryptConfig;
import org.springframework.util.StringUtils;
/**
* @author by zhangbr
* @date 2020/7/25
*/
public class FileVO {
public FileVO(String fileId, String fileName) {
if (!StringUtils.isEmpty(fileId)){
this.fileId = EncryptConfig.encrypt(fileId);
}
this.fileName = fileName;
}
@ApiModelProperty("附件ID")
private String fileId;
@ApiModelProperty("附件名称")
private String fileName;
public String getFileId() {
return fileId;
}
public void setFileId(String fileId) {
if (!StringUtils.isEmpty(fileId)){
this.fileId = EncryptConfig.encrypt(fileId);
}
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
@Override
public String toString() {
return "FileVO{" +
"fileId='" + fileId + '\'' +
'}';
}
}
package org.nafmii.common.utils; //package org.nafmii.common.utils;
//
import com.alibaba.excel.util.DateUtils; //import com.alibaba.excel.util.DateUtils;
import com.google.common.collect.Maps; //import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j; //import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils; //import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils; //import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient; //import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile; //import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply; //import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Value; //import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration; //import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile; //import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest; //import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver; //import org.springframework.web.multipart.commons.CommonsMultipartResolver;
//
import javax.servlet.http.HttpServletRequest; //import javax.servlet.http.HttpServletRequest;
import java.io.*; //import java.io.*;
import java.net.MalformedURLException; //import java.net.MalformedURLException;
import java.nio.charset.StandardCharsets; //import java.nio.charset.StandardCharsets;
import java.util.*; //import java.util.*;
//
/** ///**
* @author:zhoujh // * @author:zhoujh
* @Function:TODO // * @Function:TODO
* @date 2020/5/21 15:13 // * @date 2020/5/21 15:13
* @ClassName: // * @ClassName:
* @version: // * @version:
* @remark: // * @remark:
*/ // */
@Slf4j //@Slf4j
@Configuration //@Configuration
public class FtpUtil { //public class FtpUtil {
/**访问地址*/ // /**访问地址*/
@Value("${att.upload.path}") // @Value("${ftp.att.upload.path}")
private static String path; // private static String path;
//
/**存放地址*/ // /**存放地址*/
@Value("${att.upload.docBase}") // @Value("${ftp.att.upload.docBase}")
private static String docBase; // private static String docBase;
//
//ftp服务器地址 // //ftp服务器地址
@Value("${att.hostname}") // @Value("${ftp.att.hostname}")
private String hostname; // private String hostname;
//ftp服务器端口号默认为21 // //ftp服务器端口号默认为21
@Value("${att.port}") // @Value("${ftp.att.port}")
private Integer port; // private Integer port;
//ftp登录账号 // //ftp登录账号
@Value("${att.username}") // @Value("${ftp.att.username}")
private String username; // private String username;
//ftp登录密码 // //ftp登录密码
@Value("${att.password}") // @Value("${ftp.att.password}")
private String password; // private String password;
//
public FTPClient ftpClient = null; // public FTPClient ftpClient = null;
//
public Map<String, Object> upload(HttpServletRequest request){ // public Map<String, Object> upload(HttpServletRequest request){
final Map<String, Object> result = new HashMap<>(); // final Map<String, Object> result = new HashMap<>();
//初始化多部份解析器 // //初始化多部份解析器
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); // CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
//检查了request是否为null,请求是否为post,form中是否有enctype="multipart/form-data" // //检查了request是否为null,请求是否为post,form中是否有enctype="multipart/form-data"
if(multipartResolver.isMultipart(request)){ // if(multipartResolver.isMultipart(request)){
//转换为多部份request // //转换为多部份request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; // MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
//获取multiRequest中所有文件名 // //获取multiRequest中所有文件名
Iterator it = multiRequest.getFileNames(); // Iterator it = multiRequest.getFileNames();
while (it.hasNext()){ // while (it.hasNext()){
MultipartFile file = multiRequest.getFile(it.next().toString()); // MultipartFile file = multiRequest.getFile(it.next().toString());
if(file != null){ // if(file != null){
//获取文件名 // //获取文件名
String fileName = file.getOriginalFilename(); // String fileName = file.getOriginalFilename();
// 文件后缀 // // 文件后缀
String suffixes = fileName.substring(fileName.lastIndexOf(".")); // String suffixes = fileName.substring(fileName.lastIndexOf("."));
// 重命名文件 // // 重命名文件
String nowName = getNewName(suffixes); // String nowName = getNewName(suffixes);
final ByteArrayOutputStream fileStream = new ByteArrayOutputStream(); // final ByteArrayOutputStream fileStream = new ByteArrayOutputStream();
// 存放位置 // // 存放位置
String savePath = getFilePath(docBase, nowName); // String savePath = getFilePath(docBase, nowName);
try { // try {
// 复制文件内容 // // 复制文件内容
IOUtils.copy(file.getInputStream(), fileStream); // IOUtils.copy(file.getInputStream(), fileStream);
//向session中存入文件内容的引用,为保存文件做准备 // //向session中存入文件内容的引用,为保存文件做准备
request.getSession().setAttribute(nowName,fileStream); // request.getSession().setAttribute(nowName,fileStream);
// 复制文件 // // 复制文件
FileUtils.copyInputStreamToFile(new ByteArrayInputStream(fileStream.toByteArray()), new File(savePath)); // FileUtils.copyInputStreamToFile(new ByteArrayInputStream(fileStream.toByteArray()), new File(savePath));
} catch (Exception e) { // } catch (Exception e) {
return null; // return null;
} // }
result.put("nowName",nowName); // result.put("nowName",nowName);
result.put("savePath",savePath); // result.put("savePath",savePath);
result.put("fileSize",file.getSize()); // result.put("fileSize",file.getSize());
result.put("url",getFilePath(path,nowName)); // result.put("url",getFilePath(path,nowName));
} else { // } else {
return result; // return result;
} // }
} // }
} // }
return result; // return result;
} // }
//
public static Map<String, String> upload(String imgBase64){ // public static Map<String, String> upload(String imgBase64){
log.info("==============开始上传图片============="); // log.info("==============开始上传图片=============");
Map<String, String> result = new HashMap<>(); // Map<String, String> result = new HashMap<>();
if(imgBase64 != null){ // if(imgBase64 != null){
// 文件后缀 // // 文件后缀
String suffixes = ".jpg"; // String suffixes = ".jpg";
// 重命名 // // 重命名
String nowName = getNewName(suffixes); // String nowName = getNewName(suffixes);
// 存放位置 // // 存放位置
String savePath = getFilePath(docBase, nowName); // String savePath = getFilePath(docBase, nowName);
try { // try {
// IOUtils.copy(file.getInputStream(), fileStream); //// IOUtils.copy(file.getInputStream(), fileStream);
mkdir(savePath.substring(0,savePath.lastIndexOf("/"))); // mkdir(savePath.substring(0,savePath.lastIndexOf("/")));
FtpUtil.base64MultipartFile(imgBase64,savePath); // FtpUtil.base64MultipartFile(imgBase64,savePath);
// file.transferTo(new File(savePath)); //// file.transferTo(new File(savePath));
log.info("==============上传成功=============="); // log.info("==============上传成功==============");
} catch (Exception e) { // } catch (Exception e) {
log.error("==============出现异常,上传失败=============="); // log.error("==============出现异常,上传失败==============");
return null; // return null;
} // }
result.put("nowName",nowName); // result.put("nowName",nowName);
result.put("path",getFilePath(nowName)); // result.put("path",getFilePath(nowName));
result.put("savePath",savePath); // result.put("savePath",savePath);
// result.put("url",getFilePath(path,nowName)); //// result.put("url",getFilePath(path,nowName));
} // }
return result; // return result;
} // }
//
/** // public static void main(String[] args) {
* 初始化ftp服务器 // FtpUtil ft = new FtpUtil();
*/ // ft.initFtpClient();
public void initFtpClient() { // }
ftpClient = new FTPClient(); // /**
ftpClient.setControlEncoding("utf-8"); // * 初始化ftp服务器
try { // */
log.info("...ftp服务器:connecting"+hostname+":"+port+"...."+ DateUtils.format(new Date())); // public void initFtpClient() {
ftpClient.connect(hostname, port); //连接ftp服务器 // hostname="192.168.202.38";
if(!ftpClient.isConnected()){ // port = 21;
ftpClient.connect(hostname, port); // username = "ypenglv";
} // password = "peng1003";
ftpClient.login(username, password); //登录ftp服务器 // ftpClient = new FTPClient();
int replyCode = ftpClient.getReplyCode(); //是否成功登录服务器 // ftpClient.setControlEncoding("utf-8");
if(!FTPReply.isPositiveCompletion(replyCode)){ // try {
log.info("connect failed...ftp服务器:"+hostname+":"+port+"...."+DateUtils.format(new Date())); // log.info("...ftp服务器:connecting"+hostname+":"+port+"...."+ DateUtils.format(new Date()));
} // ftpClient.connect(hostname, port); //连接ftp服务器
log.info("connect successfu...ftp服务器:"+hostname+":"+port+"...."+DateUtils.format(new Date())); // if(!ftpClient.isConnected()){
}catch (MalformedURLException e) { // ftpClient.connect(hostname, port);
e.printStackTrace(); // }
}catch (IOException e) { // ftpClient.login(username, password); //登录ftp服务器
e.printStackTrace(); // int replyCode = ftpClient.getReplyCode(); //是否成功登录服务器
} // if(!FTPReply.isPositiveCompletion(replyCode)){
} // log.info("connect failed...ftp服务器:"+hostname+":"+port+"...."+DateUtils.format(new Date()));
// }
/** // log.info("connect successfu...ftp服务器:"+hostname+":"+port+"...."+DateUtils.format(new Date()));
* 上传文件 // }catch (MalformedURLException e) {
* @param pathname ftp服务保存地址 // e.printStackTrace();
* @param fileName 上传到ftp的文件名 // }catch (IOException e) {
* @param originfilename 待上传文件的名称(绝对地址) * // e.printStackTrace();
* @return // }
*/ // }
public boolean uploadFile( String pathname, String fileName,String originfilename){ //
boolean flag = false; // /**
InputStream inputStream = null; // * 上传文件
try{ // * @param pathname ftp服务保存地址
log.info("开始上传文件"); // * @param fileName 上传到ftp的文件名
inputStream = new FileInputStream(new File(originfilename)); // * @param originfilename 待上传文件的名称(绝对地址) *
initFtpClient(); // * @return
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); // */
CreateDirecroty(pathname); // public boolean uploadFile( String pathname, String fileName,String originfilename){
ftpClient.makeDirectory(pathname); // boolean flag = false;
ftpClient.changeWorkingDirectory(pathname); // InputStream inputStream = null;
ftpClient.storeFile(fileName, inputStream); // try{
inputStream.close(); // log.info("开始上传文件");
ftpClient.logout(); // inputStream = new FileInputStream(new File(originfilename));
flag = true; // initFtpClient();
log.info("上传文件成功"); // ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
}catch (Exception e) { // CreateDirecroty(pathname);
log.info("上传文件失败"); // ftpClient.makeDirectory(pathname);
e.printStackTrace(); // ftpClient.changeWorkingDirectory(pathname);
}finally{ // ftpClient.storeFile(fileName, inputStream);
if(ftpClient.isConnected()){ // inputStream.close();
try{ // ftpClient.logout();
ftpClient.disconnect(); // flag = true;
}catch(IOException e){ // log.info("上传文件成功");
e.printStackTrace(); // }catch (Exception e) {
} // log.info("上传文件失败");
} // e.printStackTrace();
if(null != inputStream){ // }finally{
try { // if(ftpClient.isConnected()){
inputStream.close(); // try{
} catch (IOException e) { // ftpClient.disconnect();
e.printStackTrace(); // }catch(IOException e){
} // e.printStackTrace();
} // }
} // }
return true; // if(null != inputStream){
} // try {
/** // inputStream.close();
* 上传文件 // } catch (IOException e) {
* @param path ftp服务保存地址 // e.printStackTrace();
* @param fileName 上传到ftp的文件名重命名的文件名 // }
* @param inputStream 输入文件流 // }
* @return // }
*/ // return true;
public Map<Boolean,String> uploadArrFile(String path, LinkedList<String> fileName, LinkedList<InputStream> inputStream){ // }
boolean flag = false; // /**
Map<Boolean,String> map = Maps.newHashMap(); // * 上传文件
String realPath = ""; // * @param path ftp服务保存地址
try{ // * @param fileName 上传到ftp的文件名重命名的文件名
log.info("======开始上传文件======"); // * @param inputStream 输入文件流
log.info("======上传文件地址======"+path+"====系统存储文件名=="+fileName); // * @return
initFtpClient(); // */
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); // public Map<Boolean,String> uploadArrFile(String path, LinkedList<String> fileName, LinkedList<InputStream> inputStream){
realPath = path + "/" + fileName; // boolean flag = false;
CreateDirecroty(path); // Map<Boolean,String> map = Maps.newHashMap();
ftpClient.makeDirectory(path); // String realPath = "";
ftpClient.changeWorkingDirectory(path); // try{
for(int i=0;i<fileName.size();i++){ // log.info("======开始上传文件======");
ftpClient.storeFile(fileName.get(i), inputStream.get(i)); // log.info("======上传文件地址======"+path+"====系统存储文件名=="+fileName);
inputStream.get(i).close(); // initFtpClient();
} // ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.logout(); // realPath = path + "/" + fileName;
flag = true; // CreateDirecroty(path);
log.info("======上传文件成功======"); // ftpClient.makeDirectory(path);
}catch (Exception e) { // ftpClient.changeWorkingDirectory(path);
log.error("======上传文件失败======"); // for(int i=0;i<fileName.size();i++){
e.printStackTrace(); // ftpClient.storeFile(fileName.get(i), inputStream.get(i));
}finally{ // inputStream.get(i).close();
if(ftpClient.isConnected()){ // }
try{ // ftpClient.logout();
ftpClient.disconnect(); // flag = true;
}catch(IOException e){ // log.info("======上传文件成功======");
e.printStackTrace(); // }catch (Exception e) {
} // log.error("======上传文件失败======");
} // e.printStackTrace();
for(int i=0;i<inputStream.size();i++){ // }finally{
if(null != inputStream.get(i)){ // if(ftpClient.isConnected()){
try { // try{
inputStream.get(i).close(); // ftpClient.disconnect();
} catch (IOException e) { // }catch(IOException e){
e.printStackTrace(); // e.printStackTrace();
} // }
} // }
} // for(int i=0;i<inputStream.size();i++){
} // if(null != inputStream.get(i)){
map.put(flag,realPath); // try {
return map; // inputStream.get(i).close();
} // } catch (IOException e) {
/** // e.printStackTrace();
* 上传文件 // }
* @param path ftp服务保存地址 // }
* @param fileName 上传到ftp的文件名重命名的文件名 // }
* @param inputStream 输入文件流 // }
* @return // map.put(flag,realPath);
*/ // return map;
public Map<Boolean,String> uploadFile(String path, String fileName, InputStream inputStream){ // }
boolean flag = false; // /**
Map<Boolean,String> map = Maps.newHashMap(); // * 上传文件
String realPath = ""; // * @param path ftp服务保存地址
try{ // * @param fileName 上传到ftp的文件名重命名的文件名
log.info("======开始上传文件======"); // * @param inputStream 输入文件流
log.info("======上传文件地址======"+path+"====系统存储文件名=="+fileName); // * @return
initFtpClient(); // */
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); // public Map<Boolean,String> uploadFile(String path, String fileName, InputStream inputStream){
realPath = path + "/" + fileName; // boolean flag = false;
CreateDirecroty(path); // Map<Boolean,String> map = Maps.newHashMap();
ftpClient.makeDirectory(path); // String realPath = "";
ftpClient.changeWorkingDirectory(path); // try{
ftpClient.storeFile(fileName, inputStream); // log.info("======开始上传文件======");
inputStream.close(); // log.info("======上传文件地址======"+path+"====系统存储文件名=="+fileName);
ftpClient.logout(); // initFtpClient();
flag = true; // ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
log.info("======上传文件成功======"); // realPath = path + "/" + fileName;
}catch (Exception e) { // CreateDirecroty(path);
log.error("======上传文件失败======"); // ftpClient.makeDirectory(path);
e.printStackTrace(); // ftpClient.changeWorkingDirectory(path);
}finally{ // ftpClient.storeFile(fileName, inputStream);
if(ftpClient.isConnected()){ // inputStream.close();
try{ // ftpClient.logout();
ftpClient.disconnect(); // flag = true;
}catch(IOException e){ // log.info("======上传文件成功======");
e.printStackTrace(); // }catch (Exception e) {
} // log.error("======上传文件失败======");
} // e.printStackTrace();
if(null != inputStream){ // }finally{
try { // if(ftpClient.isConnected()){
inputStream.close(); // try{
} catch (IOException e) { // ftpClient.disconnect();
e.printStackTrace(); // }catch(IOException e){
} // e.printStackTrace();
} // }
} // }
map.put(flag,realPath); // if(null != inputStream){
return map; // try {
} // inputStream.close();
//改变目录路径 // } catch (IOException e) {
public boolean changeWorkingDirectory(String directory) { // e.printStackTrace();
boolean flag = true; // }
try { // }
flag = ftpClient.changeWorkingDirectory(directory); // }
} catch (IOException ioe) { // map.put(flag,realPath);
ioe.printStackTrace(); // return map;
} // }
return flag; // //改变目录路径
} // public boolean changeWorkingDirectory(String directory) {
// boolean flag = true;
//创建多层目录文件,如果有ftp服务器已存在该文件,则不创建,如果无,则创建 // try {
public boolean CreateDirecroty(String remote) throws IOException { // flag = ftpClient.changeWorkingDirectory(directory);
boolean success = true; // } catch (IOException ioe) {
String directory = remote + "/"; // ioe.printStackTrace();
// 如果远程目录不存在,则递归创建远程服务器目录 // }
if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(directory)) { // return flag;
int start = 0; // }
int end = 0; //
if (directory.startsWith("/")) { // //创建多层目录文件,如果有ftp服务器已存在该文件,则不创建,如果无,则创建
start = 1; // public boolean CreateDirecroty(String remote) throws IOException {
} else { // boolean success = true;
start = 0; // String directory = remote + "/";
} // // 如果远程目录不存在,则递归创建远程服务器目录
end = directory.indexOf("/", start); // if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(directory)) {
String path = ""; // int start = 0;
String paths = ""; // int end = 0;
while (true) { // if (directory.startsWith("/")) {
String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), StandardCharsets.ISO_8859_1); // start = 1;
path = path + "/" + subDirectory; // } else {
if (!existFile(path)) { // start = 0;
if (makeDirectory(subDirectory)) { // }
changeWorkingDirectory(subDirectory); // end = directory.indexOf("/", start);
} else { // String path = "";
log.info("创建目录[" + subDirectory + "]失败"); // String paths = "";
changeWorkingDirectory(subDirectory); // while (true) {
} // String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), StandardCharsets.ISO_8859_1);
} else { // path = path + "/" + subDirectory;
changeWorkingDirectory(subDirectory); // if (!existFile(path)) {
} // if (makeDirectory(subDirectory)) {
// changeWorkingDirectory(subDirectory);
paths = paths + "/" + subDirectory; // } else {
start = end + 1; // log.info("创建目录[" + subDirectory + "]失败");
end = directory.indexOf("/", start); // changeWorkingDirectory(subDirectory);
// 检查所有目录是否创建完毕 // }
if (end <= start) { // } else {
break; // changeWorkingDirectory(subDirectory);
} // }
} //
} // paths = paths + "/" + subDirectory;
return success; // start = end + 1;
} // end = directory.indexOf("/", start);
// // 检查所有目录是否创建完毕
//判断ftp服务器文件是否存在 // if (end <= start) {
public boolean existFile(String path) throws IOException { // break;
boolean flag = false; // }
FTPFile[] ftpFileArr = ftpClient.listFiles(path); // }
if (ftpFileArr.length > 0) { // }
flag = true; // return success;
} // }
return flag; //
} // //判断ftp服务器文件是否存在
//创建目录 // public boolean existFile(String path) throws IOException {
public boolean makeDirectory(String dir) { // boolean flag = false;
boolean flag = true; // FTPFile[] ftpFileArr = ftpClient.listFiles(path);
try { // if (ftpFileArr.length > 0) {
flag = ftpClient.makeDirectory(dir); // flag = true;
} catch (Exception e) { // }
e.printStackTrace(); // return flag;
} // }
return flag; // //创建目录
} // public boolean makeDirectory(String dir) {
// boolean flag = true;
/** * 下载文件 * // try {
* @param pathname FTP服务器文件目录 * // flag = ftpClient.makeDirectory(dir);
* @param filename 文件名称 * // } catch (Exception e) {
* @param localpath 下载后的文件路径 * // e.printStackTrace();
* @return */ // }
public boolean downloadFile(String pathname, String filename, String localpath){ // return flag;
boolean flag = false; // }
OutputStream os=null; //
try { // /** * 下载文件 *
log.info("======开始下载文件======"); // * @param pathname FTP服务器文件目录 *
initFtpClient(); // * @param filename 文件名称 *
//切换FTP目录 // * @param localpath 下载后的文件路径 *
ftpClient.changeWorkingDirectory(pathname); // * @return */
FTPFile[] ftpFiles = ftpClient.listFiles(); // public boolean downloadFile(String pathname, String filename, String localpath){
for(FTPFile file : ftpFiles){ // boolean flag = false;
if(filename.equalsIgnoreCase(file.getName())){ // OutputStream os=null;
File localFile = new File(localpath + "/" + file.getName()); // try {
os = new FileOutputStream(localFile); // log.info("======开始下载文件======");
ftpClient.retrieveFile(file.getName(), os); // initFtpClient();
os.close(); // //切换FTP目录
} // ftpClient.changeWorkingDirectory(pathname);
} // FTPFile[] ftpFiles = ftpClient.listFiles();
ftpClient.logout(); // for(FTPFile file : ftpFiles){
flag = true; // if(filename.equalsIgnoreCase(file.getName())){
log.info("======下载文件成功======"); // File localFile = new File(localpath + "/" + file.getName());
} catch (Exception e) { // os = new FileOutputStream(localFile);
log.error("======下载文件失败======"); // ftpClient.retrieveFile(file.getName(), os);
e.printStackTrace(); // os.close();
} finally{ // }
if(ftpClient.isConnected()){ // }
try{ // ftpClient.logout();
ftpClient.disconnect(); // flag = true;
}catch(IOException e){ // log.info("======下载文件成功======");
e.printStackTrace(); // } catch (Exception e) {
} // log.error("======下载文件失败======");
} // e.printStackTrace();
if(null != os){ // } finally{
try { // if(ftpClient.isConnected()){
os.close(); // try{
} catch (IOException e) { // ftpClient.disconnect();
e.printStackTrace(); // }catch(IOException e){
} // e.printStackTrace();
} // }
} // }
return flag; // if(null != os){
} // try {
// os.close();
/** * 删除文件 * // } catch (IOException e) {
* @param pathname FTP服务器保存目录 * // e.printStackTrace();
* @param filename 要删除的文件名称 * // }
* @return */ // }
public boolean deleteFile(String pathname, String filename){ // }
boolean flag = false; // return flag;
try { // }
log.info("======开始删除文件======"); //
initFtpClient(); // /** * 删除文件 *
//切换FTP目录 // * @param pathname FTP服务器保存目录 *
ftpClient.changeWorkingDirectory(pathname); // * @param filename 要删除的文件名称 *
ftpClient.dele(filename); // * @return */
ftpClient.logout(); // public boolean deleteFile(String pathname, String filename){
flag = true; // boolean flag = false;
log.info("======删除文件成功======"); // try {
} catch (Exception e) { // log.info("======开始删除文件======");
log.error("======删除文件失败======"); // initFtpClient();
e.printStackTrace(); // //切换FTP目录
} finally { // ftpClient.changeWorkingDirectory(pathname);
if(ftpClient.isConnected()){ // ftpClient.dele(filename);
try{ // ftpClient.logout();
ftpClient.disconnect(); // flag = true;
}catch(IOException e){ // log.info("======删除文件成功======");
e.printStackTrace(); // } catch (Exception e) {
} // log.error("======删除文件失败======");
} // e.printStackTrace();
} // } finally {
return flag; // if(ftpClient.isConnected()){
} // try{
// ftpClient.disconnect();
public static void mkdir(String path) { // }catch(IOException e){
File dir = new File(path); // e.printStackTrace();
if (dir.exists()) { // }
if (!dir.isFile()) { // }
return; // }
} // return flag;
dir.delete(); // }
} //
dir.mkdirs(); // public static void mkdir(String path) {
} // File dir = new File(path);
// if (dir.exists()) {
/** // if (!dir.isFile()) {
* 获取文件绝对路径 // return;
* @param request // }
* @param host // dir.delete();
* @return // }
*/ // dir.mkdirs();
public static String getFileUrl(HttpServletRequest request, String host) { // }
String path = request.getScheme() + "://" + host + request.getContextPath() + "/"; //
int port = request.getServerPort(); // /**
if (80 != port) { // * 获取文件绝对路径
path = request.getScheme() + "://" + host + ":" + request.getServerPort() + request.getContextPath() + "/"; // * @param request
} // * @param host
return path; // * @return
} // */
// public static String getFileUrl(HttpServletRequest request, String host) {
/** // String path = request.getScheme() + "://" + host + request.getContextPath() + "/";
* 文件路径 // int port = request.getServerPort();
* @param pathname // if (80 != port) {
* @return // path = request.getScheme() + "://" + host + ":" + request.getServerPort() + request.getContextPath() + "/";
*/ // }
public static String getFilePath(String pathname) { // return path;
StringBuilder sb = new StringBuilder().append(DateUtils.format(new Date())).append("/").append(pathname); // }
return sb.toString(); //
} // /**
// * 文件路径
/** // * @param pathname
* 文件路径 // * @return
* @param filepath // */
* @param filename // public static String getFilePath(String pathname) {
* @return // StringBuilder sb = new StringBuilder().append(DateUtils.format(new Date())).append("/").append(pathname);
*/ // return sb.toString();
public static String getFilePath(String filepath, String filename) { // }
StringBuilder sb = new StringBuilder(filepath).append(DateUtils.format(new Date())).append("/").append(filename); //
return sb.toString(); // /**
} // * 文件路径
// * @param filepath
/** // * @param filename
* 文件重命名 // * @return
* @param suffixes // */
* @return // public static String getFilePath(String filepath, String filename) {
*/ // StringBuilder sb = new StringBuilder(filepath).append(DateUtils.format(new Date())).append("/").append(filename);
public static String getNewName(String suffixes){ // return sb.toString();
return UUID.randomUUID().toString().replaceAll("\\-", "") + suffixes; // }
} //
// /**
/** // * 文件重命名
* 删除文件 // * @param suffixes
* @param path // * @return
*/ // */
public static void delFiles(String path) { // public static String getNewName(String suffixes){
File file = new File(path); // return UUID.randomUUID().toString().replaceAll("\\-", "") + suffixes;
if (file.exists()) { // }
file.delete(); //
} // /**
} // * 删除文件
public static boolean base64MultipartFile(String imgStr, String imagePath){ // * @param path
if (imgStr == null){ // */
return false; // public static void delFiles(String path) {
} // File file = new File(path);
try { // if (file.exists()) {
String[] baseStr = imgStr.split(","); // file.delete();
Base64.Decoder decoder= Base64.getMimeDecoder(); // }
byte[] b = new byte[0]; // }
b = decoder.decode(baseStr[1]); // public static boolean base64MultipartFile(String imgStr, String imagePath){
for(int i = 0; i < b.length; ++i) { // if (imgStr == null){
if (b[i] < 0) { // return false;
b[i] += 256; // }
} // try {
} // String[] baseStr = imgStr.split(",");
OutputStream out = new FileOutputStream(imagePath); // Base64.Decoder decoder= Base64.getMimeDecoder();
out.write(b); // byte[] b = new byte[0];
out.flush(); // b = decoder.decode(baseStr[1]);
out.close(); // for(int i = 0; i < b.length; ++i) {
return true; // if (b[i] < 0) {
}catch (Exception e){ // b[i] += 256;
e.printStackTrace(); // }
return false; // }
} // OutputStream out = new FileOutputStream(imagePath);
} // out.write(b);
} // out.flush();
// out.close();
// return true;
// }catch (Exception e){
// e.printStackTrace();
// return false;
// }
// }
//}
org.springframework.boot.autoconfigure.EnableAutoConfiguration = \
org.nafmii.common.config.RedisConfig,\
org.nafmii.common.utils.SpringUtils,\
org.nafmii.common.config.JsonSerializerConfig,\
org.nafmii.common.exception.BusinessExceptionHandler,\
org.nafmii.common.config.EncryptConfig
\ No newline at end of file \ No newline at end of file
#ftp地址-ftp请求。
ftp.host=127.0.0.1
#ftp端口号
ftp.port=21
#ftp请求的用户名
ftp.username=ftpUser2
#ftp请求的密码
ftp.password=ftpUser2
#ftp请求读取写入的文件路径
ftp.filepath=/data/ftp
\ No newline at end of file \ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!