最近碰到一个问题,就是实现调用FTP服务器免登陆下载在进行展示,在这里分享下源码,能帮助到你的请点个赞呐呐呐!
上源码+注释
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import javax.servlet.ServletContext;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.struts2.ServletActionContext;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class FtpUatil {
private String url;
private String port;
private String username;
private String password;
private String ftpMode;
private String dir;
private String config = "";
private static String OS = System.getProperty("os.name").toLowerCase();
private FTPClient ftpClient;
public String getUrl() {
return this.url;
}
public String getPort() {
return this.port;
}
public String getFtpMode() {
return this.ftpMode;
}
public void setFtpMode(String ftpMode) {
this.ftpMode = ftpMode;
}
public FtpUtil() {
this.ftpClient = new FTPClient();
this.ftpClient.setBufferSize(1024);
this.ftpClient.setControlEncoding("UTF-8");
this.ftpClient.setDefaultTimeout(300000);
this.ftpClient.setConnectTimeout(300000);
this.ftpClient.setDataTimeout(300000);
this.ftpClient.configure(getClientConfig());
}
public void getConn(String ftpConfig) {
if (this.config.equals(ftpConfig)) {
return;
}
System.out.println("reading FTP Config...");
try {
if (ftpConfig.indexOf("/", ftpConfig.indexOf("@")) == -1) {
this.dir = "";
this.port = ftpConfig.substring(ftpConfig.indexOf(":", ftpConfig.indexOf("@")) + 1, ftpConfig.length());
} else {
this.dir = ftpConfig.substring(ftpConfig.indexOf("/", ftpConfig.indexOf("@")) + 1, ftpConfig.length());
this.port = ftpConfig.substring(ftpConfig.indexOf(":", ftpConfig.indexOf("@")) + 1,
ftpConfig.indexOf("/", ftpConfig.indexOf("@")));
}
this.url = ftpConfig.substring(ftpConfig.indexOf("@") + 1,
ftpConfig.indexOf(":", ftpConfig.indexOf("@") - 1));
this.username = ftpConfig.substring(ftpConfig.indexOf("//") + 2,
ftpConfig.indexOf(":", ftpConfig.indexOf("//")));
this.password = ftpConfig.substring(ftpConfig.indexOf(":", ftpConfig.indexOf("//")) + 1,
ftpConfig.indexOf("@"));
} catch (Exception localException) {
}
if (this.dir.equals(""))
this.config = ("ftp://" + this.username + ":" + this.password + "@" + this.url + ":" + this.port);
else {
this.config = ("ftp://" + this.username + ":" + this.password + "@" + this.url + ":" + this.port + "/"
+ this.dir);
}
System.out.println(this.config);
}
private void ftpConnect(String url, String port, String username, String password) {
System.out.println("连接" + this.config);
try {
this.ftpClient.connect(url, Integer.parseInt(port));
boolean loginResult = this.ftpClient.login(username, password);
int returnCode = this.ftpClient.getReplyCode();
if ((loginResult) && (FTPReply.isPositiveCompletion(returnCode))) {
System.out.println("ftp连接成功");
if (this.ftpMode == "PORT") {
this.ftpClient.enterLocalActiveMode();
System.out.println("ftp连接进入主动模式(PORT)");
} else {
this.ftpClient.enterLocalPassiveMode();
System.out.println("ftp连接进入被动模式(PASV)");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void ftpDisconnect() {
try {
if (this.ftpClient.isConnected()) {
this.ftpClient.logout();
this.ftpClient.disconnect();
System.out.println("关闭ftp连接");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean fileRename(String path, String oldName, String newName) throws IOException {
if (!this.ftpClient.isConnected()) {
ftpConnect(this.url, this.port, this.username, this.password);
}
System.out.println("文件重命名");
this.ftpClient.changeWorkingDirectory(this.dir + path);
return this.ftpClient.rename(oldName, newName);
}
public boolean fileDelete(String pathName) throws IOException {
if (!this.ftpClient.isConnected()) {
ftpConnect(this.url, this.port, this.username, this.password);
}
System.out.println("删除" + pathName);
boolean returnMessage = this.ftpClient.deleteFile(this.dir + pathName);
if (returnMessage) {
System.out.println("删除成功!");
}
return returnMessage;
}
public ByteArrayOutputStream fileGet(String path, String fileName) {
if (!this.ftpClient.isConnected())
ftpConnect(this.url, this.port, this.username, this.password);
try {
this.ftpClient.setControlEncoding("GBK");
this.ftpClient.setFileType(2);
this.ftpClient.changeWorkingDirectory(this.dir + path);
System.out.println("读取文件信息:" + path + "/" + fileName);
InputStream ins = this.ftpClient.retrieveFileStream(fileName);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = ins.read(buffer)) > -1) {
baos.write(buffer, 0, len);
}
baos.flush();
ins.close();
System.out.println("文件读取完成");
return baos;
} catch (NullPointerException e) {
e.printStackTrace();
System.out.println("文件不存在");
return null;
} catch (IOException e) {
e.printStackTrace();
System.out.println("文件读取发生错误");
return null;
} finally {
ftpDisconnect();
}
}
private static FTPClientConfig getClientConfig() {
String sysType = null;
if (isLinux())
sysType = "UNIX";
else if (isWindows()) {
sysType = "WINDOWS";
}
FTPClientConfig config = new FTPClientConfig(sysType);
config.setRecentDateFormatStr("yyyy-MM-dd HH:mm");
return config;
}
private static boolean isLinux() {
return OS.contains("linux");
}
private static boolean isWindows() {
return OS.contains("windows");
}
/**
* @param fileUrl
* @param pdfFileName
* @return
*/
public static String getExamPdf(String fileUrl, String pdfFileName) {
//处理fileUrl为三部分:ftp地址,dir目录,文件名
FtpUtil ftpUtil = new FtpUtil();
//用户名密码是aa/bb ftp端口号默认的是21(传输数据)
String ftpConfig = "ftp://aa:bb@ip:21";//账户密码及ftp服务器ip+端口号
ftpUtil.getConn(ftpConfig);
String dir = fileUrl.substring(20, fileUrl.indexOf("pdfbg/") + 13); //fpt服务器文件目录
//"/pathimages/pdfbg/2019-11/";
String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);//fpt服务器文件名
ByteArrayOutputStream fileData = ftpUtil.fileGet(dir, fileName);
if (fileData == null) {
return null;
}
ftpUtil.ftpDisconnect();
BASE64Encoder encode = new BASE64Encoder();
ServletContext servletContext = ServletActionContext.getServletContext();
String path = servletContext.getRealPath("/bl_pdf");
path = path + "/";//获取上下文bl_pdf文件夹的目录路径
Base64ToPdf(encode.encode(fileData.toByteArray()), pdfFileName, path);
return path + pdfFileName + ".pdf";
}
/**
* base64字符串转换成pdf
* @param pdfStr base64字符串
* @param pdfFilePath pdf存放路径
* @param pdfName pdf存放路径的文件名
* @return
* @author songhaibo
*/
public static boolean Base64ToPdf(String pdfStr, String pdfName, String pdfFilePath) {
if (StringUtils.isBlank(pdfStr))
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byte[] b = decoder.decodeBuffer(pdfStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
String fileName = pdfFilePath + pdfName + ".pdf";
OutputStream out = new FileOutputStream(fileName);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
public static void main(String[] args) {
//测试下
String newValue = "ftp://ip/pathimages/pdfbg/2019-11/1923152cg20191121032407.pdf";
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
//返回下载好的PDF路径加文件名
newValue = getExamPdf(newValue, uuid);
System.out.println(newValue);
}
}