上传和下载使用不同权限的用户 ;
1、上传下载工具类
package com.suyun.utils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Description:FTP文件上传下载工具类
*
* @Author: leo.xiong
* @CreateDate: 2021/1/6 11:58
* @Email: [email protected]
* @Since:
*/
public class FTPFileUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(FTPFileUtil.class);
private String encoding;
private FTPClient client;
private List<String> fileList;
private static final Random RANDOM = new Random();
public FTPFileUtil() {
this.encoding = "UTF-8";
this.client = new FTPClient();
this.fileList = new ArrayList<>();
}
public FTPFileUtil(String encoding) {
this.encoding = encoding;
this.client = new FTPClient();
this.fileList = new ArrayList<>();
}
/**
* 连接
*
* @param host
* @param port
* @param username
* @param password
* @return
*/
public boolean connect(String host, int port, String username, String password) {
if (StringUtils.isEmpty(host) || StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
LOGGER.error("FTPFileUtil connect params error");
return false;
}
if (client.isConnected()) {
disconnect();
}
try {
client.connect(host, port);
client.setControlEncoding(encoding);
if (FTPReply.isPositiveCompletion(client.getReplyCode())) {
if (client.login(username, password)) {
return true;
}
}
if (client.isConnected()) {
client.disconnect();
}
} catch (Exception e) {
LOGGER.error("FTPFileUtil connect error,host:{},port:{}", host, port, e);
}
return false;
}
/**
* 断开
*/
public void disconnect() {
try {
if (client.isConnected()) {
client.logout();
client.disconnect();
}
} catch (Exception e) {
LOGGER.error("FTPFileUtil disconnect error", e);
}
}
/**
* 遍历当前目录文件
*
* @param path
*/
public List<String> listFiles(String path) {
if (StringUtils.isEmpty(path)) {
LOGGER.error("FTPFileUtil listFiles path is empty");
return fileList;
}
try {
client.enterLocalPassiveMode();
client.changeWorkingDirectory(path);
for (String name : client.listNames()) {
if (!name.equals(".") && !name.equals("..") && name.indexOf(".") != -1) {
fileList.add(name);
}
}
} catch (Exception e) {
LOGGER.error("FTPFileUtil listFiles error", e);
}
return fileList;
}
/**
* 根据提供的文件夹路径,判断路径是否存在,不存在则创建爱你
*
* @param dir
* @return
* @throws IOException
*/
public boolean createDir(String dir) throws IOException {
String[] dirs = dir.split("/");
for (String path : dirs) {
if (StringUtils.isEmpty(path)) {
continue;
}
if (client.changeWorkingDirectory(path)) {
continue;
}
client.makeDirectory(path);
if (client.changeWorkingDirectory(path)) {
continue;
}
}
return Boolean.TRUE;
}
/**
* 上传文件到FTP
*
* @param dir
* @param fileName
* @param multipartFile
* @param isCover
* @return
*/
public String uploadFile(String dir, String fileName, MultipartFile multipartFile, boolean isCover) {
try {
if (multipartFile == null) {
LOGGER.warn("Upload failed, multipartFile does not exist");
return null;
}
return uploadFile(dir, fileName, multipartFile.getInputStream(), isCover);
} catch (IOException e) {
LOGGER.warn("File stream conversion failed");
return null;
}
}
/**
* 上传文件到FTP
*
* @param dir
* @param fileName
* @param file
* @param isCover
* @return
*/
public String uploadFile(String dir, String fileName, File file, boolean isCover) {
try {
if (file == null) {
LOGGER.warn("Upload failed, file does not exist");
return null;
}
return uploadFile(dir, fileName, new FileInputStream(file), isCover);
} catch (FileNotFoundException e) {
LOGGER.warn("File stream conversion failed");
return null;
}
}
private String getWorkDirectory() throws IOException {
return client.printWorkingDirectory() + "/";
}
/**
* 文件上传
*
* @param dir 上传目录
* @param fileName 上传文件名,当不能覆盖时,会添加随机数
* @param is 上传的输入流
* @param isCover 是否覆盖 FALSE不覆盖 TURE覆盖
* @return
*/
public String uploadFile(String dir, String fileName, InputStream is, boolean isCover) {
try {
if (is == null) {
LOGGER.warn("Upload failed, input stream does not exist");
return null;
}
dir = dir.endsWith("/") ? dir : dir + "/";
createDir(dir);
String workingDirectory = getWorkDirectory();
if (!isCover) {
//获取当前目录下的所有文件
List<String> listFiles = listFiles(workingDirectory);
String prefix = fileName.substring(0, fileName.lastIndexOf("."));
String suffix = fileName.substring(fileName.lastIndexOf("."));
//判断文件是否已存在,如果已存在,添加一个随机数
do {
if (listFiles.contains(fileName)) {
fileName = prefix + (prefix.endsWith("_") ? "" : "_") + RANDOM.nextInt(1000) + suffix;
}
} while (listFiles.contains(fileName));
}
//设置上传文件的类型为二进制类型
client.setFileType(FTP.BINARY_FILE_TYPE);
//设置模式很重要
client.enterLocalPassiveMode();
//上传文件
String filePath = workingDirectory + fileName;
if (client.storeFile(filePath, is)) {
return dir + fileName;
}
return null;
} catch (IOException e) {
LOGGER.warn("upload failed dir:{} fileName:{} isCover: {}", dir, fileName, isCover, e);
return null;
} finally {
try {
is.close();
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* FTP下载
*
* @param ftpPath
* @param downLoadPath
* @return
*/
public boolean download(String ftpPath, String downLoadPath) {
OutputStream os = null;
try {
os = new FileOutputStream(new File(downLoadPath));
return client.retrieveFile(ftpPath, os);
} catch (IOException e) {
LOGGER.warn("download failed ftpPath:{} downLoadPath:{}", ftpPath, downLoadPath, e);
return Boolean.FALSE;
} finally {
try {
os.close();
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2、使用Helper类
package com.suyun.modules.vehicle.helpers;
import com.suyun.utils.FTPFileUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
/**
* Description:
*
* @Author: leo.xiong
* @CreateDate: 2020/12/25 11:23
* @Email: [email protected]
* @Since:
*/
@Component
public class UDSFTPHelper {
@Value(value = "${uds.ftpAddr}")
private String ftpAddr;
@Value(value = "${intranet.uds.ftpAddr}")
private String intranetFtpAddr;
@Value(value = "${uds.ftpPort}")
private Integer ftpPort;
@Value(value = "${uds.upload.ftpUser}")
private String ftpUploadUser;
@Value(value = "${uds.upload.ftpPwd}")
private String ftpUploadPwd;
@Value(value = "${uds.download.ftpUser}")
private String ftpDownloadUser;
@Value(value = "${uds.download.ftpPwd}")
private String ftpDownloadPwd;
@Value(value = "${uds.dir}")
private String dir;
public String getFtpAddr() {
return ftpAddr;
}
public void setFtpAddr(String ftpAddr) {
this.ftpAddr = ftpAddr;
}
public Integer getFtpPort() {
return ftpPort;
}
public void setFtpPort(Integer ftpPort) {
this.ftpPort = ftpPort;
}
public String getFtpUploadUser() {
return ftpUploadUser;
}
public void setFtpUploadUser(String ftpUploadUser) {
this.ftpUploadUser = ftpUploadUser;
}
public String getFtpUploadPwd() {
return ftpUploadPwd;
}
public void setFtpUploadPwd(String ftpUploadPwd) {
this.ftpUploadPwd = ftpUploadPwd;
}
public String getFtpDownloadUser() {
return ftpDownloadUser;
}
public void setFtpDownloadUser(String ftpDownloadUser) {
this.ftpDownloadUser = ftpDownloadUser;
}
public String getFtpDownloadPwd() {
return ftpDownloadPwd;
}
public void setFtpDownloadPwd(String ftpDownloadPwd) {
this.ftpDownloadPwd = ftpDownloadPwd;
}
public String getDir() {
return dir;
}
public void setDir(String dir) {
this.dir = dir;
}
public String getIntranetFtpAddr() {
return intranetFtpAddr;
}
public void setIntranetFtpAddr(String intranetFtpAddr) {
this.intranetFtpAddr = intranetFtpAddr;
}
/**
* 获取UDS的文件信息
*
* @return
* @throws Exception
*/
public String uploadFile(MultipartFile multipartFile, String companyId, String fileName) throws Exception {
if (multipartFile == null || multipartFile.isEmpty()) {
throw new Exception("Upload failed multipart file does not exist");
}
FTPFileUtil ftp = new FTPFileUtil();
boolean isConnection = ftp.connect(intranetFtpAddr, ftpPort, ftpUploadUser, ftpUploadPwd);
if (!isConnection) {
throw new Exception("Failed to connect to FTP service intranetFtpAddr: " + intranetFtpAddr + " ftpPort: " + ftpPort + ",ftpUploadUser: " + ftpUploadUser + ",ftpUploadPwd:" + ftpUploadPwd);
}
fileName = (StringUtils.isEmpty(fileName) ? "" : (fileName + "_")) + multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
return ftp.uploadFile(dir + companyId + "/", fileName, multipartFile, Boolean.FALSE);
}
/**
* 下载FTP文件
*
* @param ftpPath
* @param downloadPath
* @return
* @throws Exception
*/
public boolean downloadFile(String ftpPath, String downloadPath) throws Exception {
if (StringUtils.isEmpty(ftpPath) || StringUtils.isEmpty(downloadPath)) {
throw new Exception("Upload failed multipart file does not exist");
}
FTPFileUtil ftp = new FTPFileUtil();
boolean isConnection = ftp.connect(intranetFtpAddr, ftpPort, ftpDownloadUser, ftpDownloadPwd);
if (!isConnection) {
throw new Exception("Failed to connect to FTP service intranetFtpAddr: " + intranetFtpAddr + " ftpPort: " + ftpPort + ",ftpUploadUser: " + ftpUploadUser + ",ftpUploadPwd:" + ftpUploadPwd);
}
return ftp.download(ftpPath, downloadPath);
}
}
3、测试类
package com.thinkgem.jeesite.test;
import com.suyun.utils.FTPFileUtil;
import java.io.File;
import java.util.Random;
/**
* Description:
*
* @Author: leo.xiong
* @CreateDate: 2021/01/06 11:50
* @Email: [email protected]
* @Since:
*/
public class FTPUtilTest {
public static void main(String[] args) throws Exception {
FTPFileUtil ftp = new FTPFileUtil();
boolean isConnection = ftp.connect("IP", 21, "存在读写权限的用户名", "存在读写权限的密码");
String ftpPath = ftp.uploadFile("/uds/" + "公司名(不同的公司使用不同的文件夹,可以不要)" + "/", "refire_242_70P_V1.0_.bin", new File("C:\\Users\\熊浪\\Desktop/refire_242_70P_V1.0_.bin"), Boolean.FALSE);
isConnection = ftp.connect("IP", 21, "只读权限的用户名", "只读权限的密码");
if (!isConnection) {
return;
}
System.out.println(ftp.download(ftpPath, "C:\\Users\\熊浪\\Desktop\\suyun/1.bin"));
}
}