1、在lib里面引入commons-net-1.4.1.jar和jakarta-oro-2.0.8.jar(此处jar具体作用不再描述)
2、直接上代码,新建FtpFileUtils 类
package com.core.ftp;
import com.util.Tool;
import org.apache.commons.net.ftp.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.MalformedURLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
public class FtpFileUtils {
private static final Logger log = LoggerFactory.getLogger(FtpFileUtils.class);
public String hostname = "xx.xx.xx.xx";
public Integer port = 21;
public String username = "admin";
public String password = "admin";
public FTPClient ftpClient = null;
/**
* 初始化ftp服务器
*/
public void initFtpClient() {
ftpClient = new FTPClient();
//ftpClient.setControlEncoding("utf-8");
try {
System.out.println("开始连接ftp服务器:" + this.hostname + ":" + this.port);
ftpClient.connect(hostname, port); // 连接ftp服务器
ftpClient.login(username, password); // 登录ftp服务器
int replyCode = ftpClient.getReplyCode(); // 是否成功登录服务器
if (!FTPReply.isPositiveCompletion(replyCode)) {
log.info("连接ftp服务器失败=" + this.hostname + ":" + this.port);
}
log.error("连接ftp服务器成功=" + this.hostname + ":" + this.port);
} 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(FTP.BINARY_FILE_TYPE);
CreateDirecroty(pathname);
ftpClient.makeDirectory(pathname);
ftpClient.changeWorkingDirectory(pathname);
ftpClient.storeFile(fileName, inputStream);
inputStream.close();
ftpClient.logout();
flag = true;
if(flag){
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();
}
}
}
return true;
}
// 改变目录路径
public boolean changeWorkingDirectory(String directory) {
boolean flag = true;
try {
flag = ftpClient.changeWorkingDirectory(directory);
if (flag) {
log.info("进入文件夹" + directory + " 成功!");
} else {
log.error("进入文件夹" + 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(new String(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"), "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);
if (flag) {
log.info("创建文件夹" + dir + " 成功!");
} else {
log.error("创建文件夹" + dir + " 失败!");
}
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
//获取指定目录下的所有文件名
public static String[] List(String pathname, String datapathname) throws IOException {
try {
FtpFileUtils ftp = new FtpFileUtils();
String[] files = ftp.getFiles(pathname,datapathname);
return files;
} catch (Exception e) {
return null;
}
}
public String[] getFiles(String pathname,String datapathname) throws IOException {
System.out.println("1111");
initFtpClient();
System.out.print(ftpClient.getReplyString());
int reply = ftpClient.getReplyCode();
System.out.println(reply+"----------replay");
boolean b = ftpClient.changeWorkingDirectory(pathname);
System.out.println(b);
ftpClient.enterLocalPassiveMode();
ftpClient.setControlEncoding("GBK");
String[] names = ftpClient.listNames(datapathname);
ftpClient.logout();
return names;
}
//获取指定文件img,并转换成io流
public static InputStream getImgPic(String imgpath,String imgname) throws IOException {
try {
FtpFileUtils ftp = new FtpFileUtils();
InputStream imgPicIo = ftp.getImgPicIo(imgpath,imgname);
return imgPicIo;
} catch (Exception e) {
return null;
}
}
public InputStream getImgPicIo(String imgpath,String imgname) throws IOException {
InputStream inputStream =null;
String ftpPath2 = new String(imgpath.getBytes("GBK"),"iso-8859-1");
initFtpClient();
ftpClient.setControlEncoding("UTF-8"); // 中文支持
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
boolean flag1 = ftpClient.changeWorkingDirectory(ftpPath2);
inputStream = ftpClient.retrieveFileStream(new String(imgname.getBytes("GBK"), "iso-8859-1"));
return inputStream;
}
}
3、直接调用FtpFileUtils 类即可
//获取指定文件夹下面所有文件名称
String[] list = FtpFileUtils.List(pathname, datapathname);
/**
* 获取ftp文件信息,并返回io流
* */
@RequestMapping("/img")
public void renderPicture(HttpServletResponse response) throws IOException {
InputStream imgPic = FtpFileUtils.getImgPic("/xxx/xxx","1.jpg");
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int n = 0;
while (-1 != (n = imgPic.read(buffer))) {
output.write(buffer, 0, n);
}
byte[] bytes1 = output.toByteArray();
try {
response.getOutputStream().write(bytes1);
}catch (Exception e){
//如果找不到图片就返回一个默认图片
try {
response.sendRedirect("/static/img/girl.gif");
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
4、前台页面显示如下所示(调用后台方法直接显示ftp图片)
<img style="width: 120px;height: 120px;padding: 2px;" src="${ctxPath}/xcxFtpimg/img" class="img-responsive"/>