import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPConnectionClosedException;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* @author Yjt
* @date 2021/4/13 15:36
* ftp文件下载工具类
*/
@Component
public class DownLoadPDFUtils {
public static String userName;
public static String passWord;
public static String ip;
public static int port;
@Value("${ftp.userName}")
public void setUserName(String userName){
DownLoadPDFUtils.userName = userName;
}
@Value("${ftp.passWord}")
public void setPassWord(String passWord){
DownLoadPDFUtils.passWord = passWord;
}
@Value("${ftp.ip}")
public void setIp(String ip){
DownLoadPDFUtils.ip = ip;
}
@Value("${ftp.port}")
public void setPort(int port){
DownLoadPDFUtils.port = port;
}
private static final Logger LOGGER = LoggerFactory.getLogger(DownLoadPDFUtils.class);
// ftp客户端
private static FTPClient ftpClient = new FTPClient();
/**
*
* 功能:根据文件名称,下载文件流
* @param filePath 文件地址
* @param fileName 文件名
* @return
* @throws IOException
*/
public static void download(String filePath, String fileName, HttpServletResponse response){
int indez;
String substr = filePath.substring(10);
String replace = substr.replace("\\", "/");
indez = replace.lastIndexOf(".");
String suffix = replace.substring(indez);
String name = fileName + suffix;
// 获取文件名称
String[] strs = replace.split("/");
String downloadFile = strs[strs.length - 1];
try {
// 设置文件ContentType类型,这样设置,会自动判断下载文件类型
response.setContentType("application/x-msdownload;");
// 设置文件头:最后一个参数是设置下载的文件名并编码为UTF-8
response.setHeader("Content-disposition", "attachment; filename=" + new String(name.getBytes("GBK"), "ISO-8859-1"));
// 建立连接
connectToServer();
ftpClient.enterLocalPassiveMode();
// 设置传输二进制文件
int reply = ftpClient.getReplyCode();
ftpClient.changeWorkingDirectory(replace);
if(!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
throw new IOException("failed to connect to the FTP Server:");
}
// 此句代码适用Linux的FTP服务器
// String newPath = new String(downloadFile.getBytes("UTF-8"),"ISO-8859-1");
// ftp文件获取文件
InputStream is = null;
BufferedInputStream bis = null;
try {
is = ftpClient.retrieveFileStream(replace);//文件路径
bis = new BufferedInputStream(is);
OutputStream out = response.getOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while ((len = bis.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.flush();
} catch (Exception e) {
System.out.println("路径中的文件不存在!");
e.printStackTrace();
} finally {
closeConnect();
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (FTPConnectionClosedException e) {
LOGGER.error("ftp连接被关闭!", e);
try {
throw e;
} catch (FTPConnectionClosedException ftpConnectionClosedException) {
ftpConnectionClosedException.printStackTrace();
}
} catch (Exception e) {
LOGGER.error("ERR : upload file "+ fileName+ " from ftp : failed!", e);
}
}
/**
*
* 功能:关闭连接
*/
public static void closeConnect() {
try {
if (ftpClient != null) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (Exception e) {
LOGGER.error("ftp连接关闭失败!", e);
}
}
/**
* 连接到ftp服务器
*/
private static void connectToServer() throws Exception {
if (!ftpClient.isConnected()) {
int reply;
try {
ftpClient=new FTPClient();
ftpClient.connect(ip,port);
ftpClient.login(userName,passWord);
ftpClient.setControlEncoding("UTF-8");//中文编码
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);//转码
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
LOGGER.info("connectToServer FTP server refused connection.");
}
}catch(FTPConnectionClosedException ex){
LOGGER.error("服务器:IP:"+ip+"没有连接数!there are too many connected users,please try later", ex);
throw ex;
}catch (Exception e) {
LOGGER.error("登录ftp服务器【"+ip+"】失败", e);
throw e;
}
}
}
}
ftp文件下载工具类(client)
最新推荐文章于 2025-04-20 19:29:58 发布