Commit c6cebdb2 by ypenglv

FTP

1 parent ed7ce71d
package org.nafmii.app;
import org.mybatis.spring.annotation.MapperScan;
import org.nafmii.common.ftp.EnableFtpServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
......@@ -10,6 +11,7 @@ import org.springframework.cloud.openfeign.EnableFeignClients;
@EnableEurekaClient
@EnableFeignClients
@MapperScan("org.nafmii.app/**/dao")
@EnableFtpServer
public class NafmiiAppApplication {
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;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.nafmii.app.user.dto.LoginDto;
......@@ -8,13 +10,17 @@ import org.nafmii.app.user.param.LoginParam;
import org.nafmii.app.user.param.RegisterParam;
import org.nafmii.app.user.service.UserService;
import org.nafmii.app.user.vo.UserVO;
import org.nafmii.common.ftp.FTPClientHelper;
import org.nafmii.common.response.ApiResponse;
import org.nafmii.common.utils.BeanTransferUtils;
import org.nafmii.common.utils.RequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import sun.net.ftp.FtpClient;
import javax.annotation.Resource;
import java.io.File;
/**
* @author:zhoujh
......@@ -27,10 +33,12 @@ import javax.annotation.Resource;
@RestController
@RequestMapping("/app/nafmii/user")
@Api(tags = "2.0.1", description = "用户登陆注册操作操作【zjh】")
public class UserController {
@Resource
private UserService userService;
@Resource
private TestClinet testClinet;
@ApiOperation( value = "模拟用户登陆",notes = "模拟用户登陆")
@PostMapping("/loginTest")
@ResponseBody
......@@ -54,6 +62,24 @@ public class UserController {
ApiResponse<UserVO> login = userService.userLogin(loginParam);
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:
pool-name: NFMII_HikariCP
connection-test-query: SELECT 1
redis:
# Redis数据库索引(默认为0)
# Redis数据库索引(默认为0)
database: 0
# Redis服务器地址
# Redis服务器地址
host: 127.0.0.1
port: 6379
# Redis服务器连接密码(默认为空)
# Redis服务器连接密码(默认为空)
password:
jedis:
pool:
# 连接池最大连接数(使用负值表示没有限制)
# 连接池最大连接数(使用负值表示没有限制)
max-active: 20
max-wait: -1ms
max-idle: 10
......@@ -50,7 +50,12 @@ spring:
client:
enabled: true
sampler:
probability: 1.0 #zipkin采集率 0.1表示 10%采集率
probability: 1.0 #zipkin采集率 0.1表示 10%采集率
nafmii:
log-path: D:/NAFMII
dao-uri: org.nafmii.app
ftp:
host: 127.0.0.1
password: peng1003
prot: 21
username: ypenglv
\ No newline at end of file
......@@ -18,6 +18,7 @@
<fastjson.version>1.2.58</fastjson.version>
<ojdbc.version>10.2.0.4</ojdbc.version>
<jjwt.version>0.9.1</jjwt.version>
<jasypt.version>3.0.2</jasypt.version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign -->
......@@ -215,7 +216,28 @@
<artifactId>HikariCP</artifactId>
<version>4.0.0</version>
</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>
<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
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;
import com.alibaba.excel.util.DateUtils;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.MalformedURLException;
import java.nio.charset.StandardCharsets;
import java.util.*;
/**
* @author:zhoujh
* @Function:TODO
* @date 2020/5/21 15:13
* @ClassName:
* @version:
* @remark:
*/
@Slf4j
@Configuration
public class FtpUtil {
/**访问地址*/
@Value("${att.upload.path}")
private static String path;
/**存放地址*/
@Value("${att.upload.docBase}")
private static String docBase;
//ftp服务器地址
@Value("${att.hostname}")
private String hostname;
//ftp服务器端口号默认为21
@Value("${att.port}")
private Integer port;
//ftp登录账号
@Value("${att.username}")
private String username;
//ftp登录密码
@Value("${att.password}")
private String password;
public FTPClient ftpClient = null;
public Map<String, Object> upload(HttpServletRequest request){
final Map<String, Object> result = new HashMap<>();
//初始化多部份解析器
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
//检查了request是否为null,请求是否为post,form中是否有enctype="multipart/form-data"
if(multipartResolver.isMultipart(request)){
//转换为多部份request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
//获取multiRequest中所有文件名
Iterator it = multiRequest.getFileNames();
while (it.hasNext()){
MultipartFile file = multiRequest.getFile(it.next().toString());
if(file != null){
//获取文件名
String fileName = file.getOriginalFilename();
// 文件后缀
String suffixes = fileName.substring(fileName.lastIndexOf("."));
// 重命名文件
String nowName = getNewName(suffixes);
final ByteArrayOutputStream fileStream = new ByteArrayOutputStream();
// 存放位置
String savePath = getFilePath(docBase, nowName);
try {
// 复制文件内容
IOUtils.copy(file.getInputStream(), fileStream);
//向session中存入文件内容的引用,为保存文件做准备
request.getSession().setAttribute(nowName,fileStream);
// 复制文件
FileUtils.copyInputStreamToFile(new ByteArrayInputStream(fileStream.toByteArray()), new File(savePath));
} catch (Exception e) {
return null;
}
result.put("nowName",nowName);
result.put("savePath",savePath);
result.put("fileSize",file.getSize());
result.put("url",getFilePath(path,nowName));
} else {
return result;
}
}
}
return result;
}
public static Map<String, String> upload(String imgBase64){
log.info("==============开始上传图片=============");
Map<String, String> result = new HashMap<>();
if(imgBase64 != null){
// 文件后缀
String suffixes = ".jpg";
// 重命名
String nowName = getNewName(suffixes);
// 存放位置
String savePath = getFilePath(docBase, nowName);
try {
//package org.nafmii.common.utils;
//
//import com.alibaba.excel.util.DateUtils;
//import com.google.common.collect.Maps;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.io.FileUtils;
//import org.apache.commons.io.IOUtils;
//import org.apache.commons.net.ftp.FTPClient;
//import org.apache.commons.net.ftp.FTPFile;
//import org.apache.commons.net.ftp.FTPReply;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.web.multipart.MultipartFile;
//import org.springframework.web.multipart.MultipartHttpServletRequest;
//import org.springframework.web.multipart.commons.CommonsMultipartResolver;
//
//import javax.servlet.http.HttpServletRequest;
//import java.io.*;
//import java.net.MalformedURLException;
//import java.nio.charset.StandardCharsets;
//import java.util.*;
//
///**
// * @author:zhoujh
// * @Function:TODO
// * @date 2020/5/21 15:13
// * @ClassName:
// * @version:
// * @remark:
// */
//@Slf4j
//@Configuration
//public class FtpUtil {
// /**访问地址*/
// @Value("${ftp.att.upload.path}")
// private static String path;
//
// /**存放地址*/
// @Value("${ftp.att.upload.docBase}")
// private static String docBase;
//
// //ftp服务器地址
// @Value("${ftp.att.hostname}")
// private String hostname;
// //ftp服务器端口号默认为21
// @Value("${ftp.att.port}")
// private Integer port;
// //ftp登录账号
// @Value("${ftp.att.username}")
// private String username;
// //ftp登录密码
// @Value("${ftp.att.password}")
// private String password;
//
// public FTPClient ftpClient = null;
//
// public Map<String, Object> upload(HttpServletRequest request){
// final Map<String, Object> result = new HashMap<>();
// //初始化多部份解析器
// CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
// //检查了request是否为null,请求是否为post,form中是否有enctype="multipart/form-data"
// if(multipartResolver.isMultipart(request)){
// //转换为多部份request
// MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
// //获取multiRequest中所有文件名
// Iterator it = multiRequest.getFileNames();
// while (it.hasNext()){
// MultipartFile file = multiRequest.getFile(it.next().toString());
// if(file != null){
// //获取文件名
// String fileName = file.getOriginalFilename();
// // 文件后缀
// String suffixes = fileName.substring(fileName.lastIndexOf("."));
// // 重命名文件
// String nowName = getNewName(suffixes);
// final ByteArrayOutputStream fileStream = new ByteArrayOutputStream();
// // 存放位置
// String savePath = getFilePath(docBase, nowName);
// try {
// // 复制文件内容
// IOUtils.copy(file.getInputStream(), fileStream);
mkdir(savePath.substring(0,savePath.lastIndexOf("/")));
FtpUtil.base64MultipartFile(imgBase64,savePath);
// file.transferTo(new File(savePath));
log.info("==============上传成功==============");
} catch (Exception e) {
log.error("==============出现异常,上传失败==============");
return null;
}
result.put("nowName",nowName);
result.put("path",getFilePath(nowName));
result.put("savePath",savePath);
// //向session中存入文件内容的引用,为保存文件做准备
// request.getSession().setAttribute(nowName,fileStream);
// // 复制文件
// FileUtils.copyInputStreamToFile(new ByteArrayInputStream(fileStream.toByteArray()), new File(savePath));
// } catch (Exception e) {
// return null;
// }
// result.put("nowName",nowName);
// result.put("savePath",savePath);
// result.put("fileSize",file.getSize());
// result.put("url",getFilePath(path,nowName));
}
return result;
}
/**
* 初始化ftp服务器
*/
public void initFtpClient() {
ftpClient = new FTPClient();
ftpClient.setControlEncoding("utf-8");
try {
log.info("...ftp服务器:connecting"+hostname+":"+port+"...."+ DateUtils.format(new Date()));
ftpClient.connect(hostname, port); //连接ftp服务器
if(!ftpClient.isConnected()){
ftpClient.connect(hostname, port);
}
ftpClient.login(username, password); //登录ftp服务器
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) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
/**
* 上传文件
* @param pathname ftp服务保存地址
* @param fileName 上传到ftp的文件名
* @param originfilename 待上传文件的名称(绝对地址) *
* @return
*/
public boolean uploadFile( String pathname, String fileName,String originfilename){
boolean flag = false;
InputStream inputStream = null;
try{
log.info("开始上传文件");
inputStream = new FileInputStream(new File(originfilename));
initFtpClient();
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
CreateDirecroty(pathname);
ftpClient.makeDirectory(pathname);
ftpClient.changeWorkingDirectory(pathname);
ftpClient.storeFile(fileName, inputStream);
inputStream.close();
ftpClient.logout();
flag = true;
log.info("上传文件成功");
}catch (Exception e) {
log.info("上传文件失败");
e.printStackTrace();
}finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOException e){
e.printStackTrace();
}
}
if(null != inputStream){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
/**
* 上传文件
* @param path ftp服务保存地址
* @param fileName 上传到ftp的文件名重命名的文件名
* @param inputStream 输入文件流
* @return
*/
public Map<Boolean,String> uploadArrFile(String path, LinkedList<String> fileName, LinkedList<InputStream> inputStream){
boolean flag = false;
Map<Boolean,String> map = Maps.newHashMap();
String realPath = "";
try{
log.info("======开始上传文件======");
log.info("======上传文件地址======"+path+"====系统存储文件名=="+fileName);
initFtpClient();
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
realPath = path + "/" + fileName;
CreateDirecroty(path);
ftpClient.makeDirectory(path);
ftpClient.changeWorkingDirectory(path);
for(int i=0;i<fileName.size();i++){
ftpClient.storeFile(fileName.get(i), inputStream.get(i));
inputStream.get(i).close();
}
ftpClient.logout();
flag = true;
log.info("======上传文件成功======");
}catch (Exception e) {
log.error("======上传文件失败======");
e.printStackTrace();
}finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOException e){
e.printStackTrace();
}
}
for(int i=0;i<inputStream.size();i++){
if(null != inputStream.get(i)){
try {
inputStream.get(i).close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
map.put(flag,realPath);
return map;
}
/**
* 上传文件
* @param path ftp服务保存地址
* @param fileName 上传到ftp的文件名重命名的文件名
* @param inputStream 输入文件流
* @return
*/
public Map<Boolean,String> uploadFile(String path, String fileName, InputStream inputStream){
boolean flag = false;
Map<Boolean,String> map = Maps.newHashMap();
String realPath = "";
try{
log.info("======开始上传文件======");
log.info("======上传文件地址======"+path+"====系统存储文件名=="+fileName);
initFtpClient();
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
realPath = path + "/" + fileName;
CreateDirecroty(path);
ftpClient.makeDirectory(path);
ftpClient.changeWorkingDirectory(path);
ftpClient.storeFile(fileName, inputStream);
inputStream.close();
ftpClient.logout();
flag = true;
log.info("======上传文件成功======");
}catch (Exception e) {
log.error("======上传文件失败======");
e.printStackTrace();
}finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOException e){
e.printStackTrace();
}
}
if(null != inputStream){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
map.put(flag,realPath);
return map;
}
//改变目录路径
public boolean changeWorkingDirectory(String directory) {
boolean flag = true;
try {
flag = ftpClient.changeWorkingDirectory(directory);
} catch (IOException ioe) {
ioe.printStackTrace();
}
return flag;
}
//创建多层目录文件,如果有ftp服务器已存在该文件,则不创建,如果无,则创建
public boolean CreateDirecroty(String remote) throws IOException {
boolean success = true;
String directory = remote + "/";
// 如果远程目录不存在,则递归创建远程服务器目录
if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(directory)) {
int start = 0;
int end = 0;
if (directory.startsWith("/")) {
start = 1;
} else {
start = 0;
}
end = directory.indexOf("/", start);
String path = "";
String paths = "";
while (true) {
String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), StandardCharsets.ISO_8859_1);
path = path + "/" + subDirectory;
if (!existFile(path)) {
if (makeDirectory(subDirectory)) {
changeWorkingDirectory(subDirectory);
} else {
log.info("创建目录[" + subDirectory + "]失败");
changeWorkingDirectory(subDirectory);
}
} else {
changeWorkingDirectory(subDirectory);
}
paths = paths + "/" + subDirectory;
start = end + 1;
end = directory.indexOf("/", start);
// 检查所有目录是否创建完毕
if (end <= start) {
break;
}
}
}
return success;
}
//判断ftp服务器文件是否存在
public boolean existFile(String path) throws IOException {
boolean flag = false;
FTPFile[] ftpFileArr = ftpClient.listFiles(path);
if (ftpFileArr.length > 0) {
flag = true;
}
return flag;
}
//创建目录
public boolean makeDirectory(String dir) {
boolean flag = true;
try {
flag = ftpClient.makeDirectory(dir);
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/** * 下载文件 *
* @param pathname FTP服务器文件目录 *
* @param filename 文件名称 *
* @param localpath 下载后的文件路径 *
* @return */
public boolean downloadFile(String pathname, String filename, String localpath){
boolean flag = false;
OutputStream os=null;
try {
log.info("======开始下载文件======");
initFtpClient();
//切换FTP目录
ftpClient.changeWorkingDirectory(pathname);
FTPFile[] ftpFiles = ftpClient.listFiles();
for(FTPFile file : ftpFiles){
if(filename.equalsIgnoreCase(file.getName())){
File localFile = new File(localpath + "/" + file.getName());
os = new FileOutputStream(localFile);
ftpClient.retrieveFile(file.getName(), os);
os.close();
}
}
ftpClient.logout();
flag = true;
log.info("======下载文件成功======");
} catch (Exception e) {
log.error("======下载文件失败======");
e.printStackTrace();
} finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOException e){
e.printStackTrace();
}
}
if(null != os){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return flag;
}
/** * 删除文件 *
* @param pathname FTP服务器保存目录 *
* @param filename 要删除的文件名称 *
* @return */
public boolean deleteFile(String pathname, String filename){
boolean flag = false;
try {
log.info("======开始删除文件======");
initFtpClient();
//切换FTP目录
ftpClient.changeWorkingDirectory(pathname);
ftpClient.dele(filename);
ftpClient.logout();
flag = true;
log.info("======删除文件成功======");
} catch (Exception e) {
log.error("======删除文件失败======");
e.printStackTrace();
} finally {
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOException e){
e.printStackTrace();
}
}
}
return flag;
}
public static void mkdir(String path) {
File dir = new File(path);
if (dir.exists()) {
if (!dir.isFile()) {
return;
}
dir.delete();
}
dir.mkdirs();
}
/**
* 获取文件绝对路径
* @param request
* @param host
* @return
*/
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() + "/";
}
return path;
}
/**
* 文件路径
* @param pathname
* @return
*/
public static String getFilePath(String pathname) {
StringBuilder sb = new StringBuilder().append(DateUtils.format(new Date())).append("/").append(pathname);
return sb.toString();
}
/**
* 文件路径
* @param filepath
* @param filename
* @return
*/
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 suffixes
* @return
*/
public static String getNewName(String suffixes){
return UUID.randomUUID().toString().replaceAll("\\-", "") + suffixes;
}
/**
* 删除文件
* @param path
*/
public static void delFiles(String path) {
File file = new File(path);
if (file.exists()) {
file.delete();
}
}
public static boolean base64MultipartFile(String imgStr, String imagePath){
if (imgStr == null){
return false;
}
try {
String[] baseStr = imgStr.split(",");
Base64.Decoder decoder= Base64.getMimeDecoder();
byte[] b = new byte[0];
b = decoder.decode(baseStr[1]);
for(int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
OutputStream out = new FileOutputStream(imagePath);
out.write(b);
out.flush();
out.close();
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
}
// } else {
// return result;
// }
// }
// }
// return result;
// }
//
// public static Map<String, String> upload(String imgBase64){
// log.info("==============开始上传图片=============");
// Map<String, String> result = new HashMap<>();
// if(imgBase64 != null){
// // 文件后缀
// String suffixes = ".jpg";
// // 重命名
// String nowName = getNewName(suffixes);
// // 存放位置
// String savePath = getFilePath(docBase, nowName);
// try {
//// IOUtils.copy(file.getInputStream(), fileStream);
// mkdir(savePath.substring(0,savePath.lastIndexOf("/")));
// FtpUtil.base64MultipartFile(imgBase64,savePath);
//// file.transferTo(new File(savePath));
// log.info("==============上传成功==============");
// } catch (Exception e) {
// log.error("==============出现异常,上传失败==============");
// return null;
// }
// result.put("nowName",nowName);
// result.put("path",getFilePath(nowName));
// result.put("savePath",savePath);
//// result.put("url",getFilePath(path,nowName));
// }
// return result;
// }
//
// public static void main(String[] args) {
// FtpUtil ft = new FtpUtil();
// ft.initFtpClient();
// }
// /**
// * 初始化ftp服务器
// */
// public void initFtpClient() {
// hostname="192.168.202.38";
// port = 21;
// username = "ypenglv";
// password = "peng1003";
// ftpClient = new FTPClient();
// ftpClient.setControlEncoding("utf-8");
// try {
// log.info("...ftp服务器:connecting"+hostname+":"+port+"...."+ DateUtils.format(new Date()));
// ftpClient.connect(hostname, port); //连接ftp服务器
// if(!ftpClient.isConnected()){
// ftpClient.connect(hostname, port);
// }
// ftpClient.login(username, password); //登录ftp服务器
// 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) {
// e.printStackTrace();
// }catch (IOException e) {
// e.printStackTrace();
// }
// }
//
// /**
// * 上传文件
// * @param pathname ftp服务保存地址
// * @param fileName 上传到ftp的文件名
// * @param originfilename 待上传文件的名称(绝对地址) *
// * @return
// */
// public boolean uploadFile( String pathname, String fileName,String originfilename){
// boolean flag = false;
// InputStream inputStream = null;
// try{
// log.info("开始上传文件");
// inputStream = new FileInputStream(new File(originfilename));
// initFtpClient();
// ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
// CreateDirecroty(pathname);
// ftpClient.makeDirectory(pathname);
// ftpClient.changeWorkingDirectory(pathname);
// ftpClient.storeFile(fileName, inputStream);
// inputStream.close();
// ftpClient.logout();
// flag = true;
// log.info("上传文件成功");
// }catch (Exception e) {
// log.info("上传文件失败");
// e.printStackTrace();
// }finally{
// if(ftpClient.isConnected()){
// try{
// ftpClient.disconnect();
// }catch(IOException e){
// e.printStackTrace();
// }
// }
// if(null != inputStream){
// try {
// inputStream.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
// return true;
// }
// /**
// * 上传文件
// * @param path ftp服务保存地址
// * @param fileName 上传到ftp的文件名重命名的文件名
// * @param inputStream 输入文件流
// * @return
// */
// public Map<Boolean,String> uploadArrFile(String path, LinkedList<String> fileName, LinkedList<InputStream> inputStream){
// boolean flag = false;
// Map<Boolean,String> map = Maps.newHashMap();
// String realPath = "";
// try{
// log.info("======开始上传文件======");
// log.info("======上传文件地址======"+path+"====系统存储文件名=="+fileName);
// initFtpClient();
// ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
// realPath = path + "/" + fileName;
// CreateDirecroty(path);
// ftpClient.makeDirectory(path);
// ftpClient.changeWorkingDirectory(path);
// for(int i=0;i<fileName.size();i++){
// ftpClient.storeFile(fileName.get(i), inputStream.get(i));
// inputStream.get(i).close();
// }
// ftpClient.logout();
// flag = true;
// log.info("======上传文件成功======");
// }catch (Exception e) {
// log.error("======上传文件失败======");
// e.printStackTrace();
// }finally{
// if(ftpClient.isConnected()){
// try{
// ftpClient.disconnect();
// }catch(IOException e){
// e.printStackTrace();
// }
// }
// for(int i=0;i<inputStream.size();i++){
// if(null != inputStream.get(i)){
// try {
// inputStream.get(i).close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
// }
// map.put(flag,realPath);
// return map;
// }
// /**
// * 上传文件
// * @param path ftp服务保存地址
// * @param fileName 上传到ftp的文件名重命名的文件名
// * @param inputStream 输入文件流
// * @return
// */
// public Map<Boolean,String> uploadFile(String path, String fileName, InputStream inputStream){
// boolean flag = false;
// Map<Boolean,String> map = Maps.newHashMap();
// String realPath = "";
// try{
// log.info("======开始上传文件======");
// log.info("======上传文件地址======"+path+"====系统存储文件名=="+fileName);
// initFtpClient();
// ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
// realPath = path + "/" + fileName;
// CreateDirecroty(path);
// ftpClient.makeDirectory(path);
// ftpClient.changeWorkingDirectory(path);
// ftpClient.storeFile(fileName, inputStream);
// inputStream.close();
// ftpClient.logout();
// flag = true;
// log.info("======上传文件成功======");
// }catch (Exception e) {
// log.error("======上传文件失败======");
// e.printStackTrace();
// }finally{
// if(ftpClient.isConnected()){
// try{
// ftpClient.disconnect();
// }catch(IOException e){
// e.printStackTrace();
// }
// }
// if(null != inputStream){
// try {
// inputStream.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
// map.put(flag,realPath);
// return map;
// }
// //改变目录路径
// public boolean changeWorkingDirectory(String directory) {
// boolean flag = true;
// try {
// flag = ftpClient.changeWorkingDirectory(directory);
// } catch (IOException ioe) {
// ioe.printStackTrace();
// }
// return flag;
// }
//
// //创建多层目录文件,如果有ftp服务器已存在该文件,则不创建,如果无,则创建
// public boolean CreateDirecroty(String remote) throws IOException {
// boolean success = true;
// String directory = remote + "/";
// // 如果远程目录不存在,则递归创建远程服务器目录
// if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(directory)) {
// int start = 0;
// int end = 0;
// if (directory.startsWith("/")) {
// start = 1;
// } else {
// start = 0;
// }
// end = directory.indexOf("/", start);
// String path = "";
// String paths = "";
// while (true) {
// String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), StandardCharsets.ISO_8859_1);
// path = path + "/" + subDirectory;
// if (!existFile(path)) {
// if (makeDirectory(subDirectory)) {
// changeWorkingDirectory(subDirectory);
// } else {
// log.info("创建目录[" + subDirectory + "]失败");
// changeWorkingDirectory(subDirectory);
// }
// } else {
// changeWorkingDirectory(subDirectory);
// }
//
// paths = paths + "/" + subDirectory;
// start = end + 1;
// end = directory.indexOf("/", start);
// // 检查所有目录是否创建完毕
// if (end <= start) {
// break;
// }
// }
// }
// return success;
// }
//
// //判断ftp服务器文件是否存在
// public boolean existFile(String path) throws IOException {
// boolean flag = false;
// FTPFile[] ftpFileArr = ftpClient.listFiles(path);
// if (ftpFileArr.length > 0) {
// flag = true;
// }
// return flag;
// }
// //创建目录
// public boolean makeDirectory(String dir) {
// boolean flag = true;
// try {
// flag = ftpClient.makeDirectory(dir);
// } catch (Exception e) {
// e.printStackTrace();
// }
// return flag;
// }
//
// /** * 下载文件 *
// * @param pathname FTP服务器文件目录 *
// * @param filename 文件名称 *
// * @param localpath 下载后的文件路径 *
// * @return */
// public boolean downloadFile(String pathname, String filename, String localpath){
// boolean flag = false;
// OutputStream os=null;
// try {
// log.info("======开始下载文件======");
// initFtpClient();
// //切换FTP目录
// ftpClient.changeWorkingDirectory(pathname);
// FTPFile[] ftpFiles = ftpClient.listFiles();
// for(FTPFile file : ftpFiles){
// if(filename.equalsIgnoreCase(file.getName())){
// File localFile = new File(localpath + "/" + file.getName());
// os = new FileOutputStream(localFile);
// ftpClient.retrieveFile(file.getName(), os);
// os.close();
// }
// }
// ftpClient.logout();
// flag = true;
// log.info("======下载文件成功======");
// } catch (Exception e) {
// log.error("======下载文件失败======");
// e.printStackTrace();
// } finally{
// if(ftpClient.isConnected()){
// try{
// ftpClient.disconnect();
// }catch(IOException e){
// e.printStackTrace();
// }
// }
// if(null != os){
// try {
// os.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
// return flag;
// }
//
// /** * 删除文件 *
// * @param pathname FTP服务器保存目录 *
// * @param filename 要删除的文件名称 *
// * @return */
// public boolean deleteFile(String pathname, String filename){
// boolean flag = false;
// try {
// log.info("======开始删除文件======");
// initFtpClient();
// //切换FTP目录
// ftpClient.changeWorkingDirectory(pathname);
// ftpClient.dele(filename);
// ftpClient.logout();
// flag = true;
// log.info("======删除文件成功======");
// } catch (Exception e) {
// log.error("======删除文件失败======");
// e.printStackTrace();
// } finally {
// if(ftpClient.isConnected()){
// try{
// ftpClient.disconnect();
// }catch(IOException e){
// e.printStackTrace();
// }
// }
// }
// return flag;
// }
//
// public static void mkdir(String path) {
// File dir = new File(path);
// if (dir.exists()) {
// if (!dir.isFile()) {
// return;
// }
// dir.delete();
// }
// dir.mkdirs();
// }
//
// /**
// * 获取文件绝对路径
// * @param request
// * @param host
// * @return
// */
// 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() + "/";
// }
// return path;
// }
//
// /**
// * 文件路径
// * @param pathname
// * @return
// */
// public static String getFilePath(String pathname) {
// StringBuilder sb = new StringBuilder().append(DateUtils.format(new Date())).append("/").append(pathname);
// return sb.toString();
// }
//
// /**
// * 文件路径
// * @param filepath
// * @param filename
// * @return
// */
// 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 suffixes
// * @return
// */
// public static String getNewName(String suffixes){
// return UUID.randomUUID().toString().replaceAll("\\-", "") + suffixes;
// }
//
// /**
// * 删除文件
// * @param path
// */
// public static void delFiles(String path) {
// File file = new File(path);
// if (file.exists()) {
// file.delete();
// }
// }
// public static boolean base64MultipartFile(String imgStr, String imagePath){
// if (imgStr == null){
// return false;
// }
// try {
// String[] baseStr = imgStr.split(",");
// Base64.Decoder decoder= Base64.getMimeDecoder();
// byte[] b = new byte[0];
// b = decoder.decode(baseStr[1]);
// for(int i = 0; i < b.length; ++i) {
// if (b[i] < 0) {
// b[i] += 256;
// }
// }
// 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
#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
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!