其中 FtpUtils 是封装的工具类,最下面两个是调用的方法的示例
public class FtpUtils {
private FTPClient ftpClient = null;
private String server=new Global().getConfig(“ftpAddress”);
private int port=Integer.parseInt(new Global().getConfig(“ftpPort”));
private String userName=new Global().getConfig(“ftpName”);
private String userPassword=new Global().getConfig(“ftpPassword”);
/**
* @description: FTP文件上传
* @author webmaster@tank.org
* @date 2018年5月3日 下午10:48:05
* @param path FTP服务器保存目录
* @param filename 上传到FTP服务器上的文件名
* @param input 输入流
* @return
*/
public boolean uploadFile( String path, String filename, InputStream input){
boolean success = false;
FTPClient ftp = new FTPClient();
ftp.setControlEncoding(“GBK”);
try {
int reply;
ftp.connect(server, port);// 连接FTP服务器
// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftp.login(userName, userPassword);// 登录
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
this.mkDir(path);
ftp.changeWorkingDirectory(path);
ftp.storeFile(filename, input);
input.close();
ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
/**
* 连接服务器
* @return 连接成功与否 true:成功, false:失败
*/
public boolean open() {
if (ftpClient != null && ftpClient.isConnected()) {
return true;
}
try {
ftpClient = new FTPClient();
// 连接
ftpClient.connect(this.server, this.port);
ftpClient.login(this.userName, this.userPassword);
setFtpClient(ftpClient);
// 检测连接是否成功
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
this.close();
// System.err.println(“FTP server refused connection.”);
// System.exit(1);
}
// System.out.println(“open FTP success:” + this.server + “;port:” + this.port + “;name:” + this.userName
// + “;pwd:” + this.userPassword);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // 设置上传模式.binally or ascii
return true;
} catch (Exception ex) {
this.close();
ex.printStackTrace();
return false;
}
}
/**
* 切换到父目录
* @return 切换结果 true:成功, false:失败
*/
private boolean changeToParentDir() {
try {
return ftpClient.changeToParentDirectory();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 改变当前目录到指定目录
* @param dir 目的目录
* @return 切换结果 true:成功,false:失败
*/
private boolean cd(String dir) {
try {
return ftpClient.changeWorkingDirectory(dir);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 获取目录下所有的文件名称
*
* @param filePath 指定的目录
* @return 文件列表,或者null
*/
private FTPFile[] getFileList(String filePath) {
try {
return ftpClient.listFiles(filePath);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 层层切换工作目录
* @param ftpPath 目的目录
* @return 切换结果
*/
public boolean changeDir(String ftpPath) {
if (!ftpClient.isConnected()) {
return false;
}
try {
// 将路径中的斜杠统一
char[] chars = ftpPath.toCharArray();
StringBuffer sbStr = new StringBuffer(256);
for (int i = 0; i < chars.length; i++) {
if ('\\' == chars[i]) {
sbStr.append('/');
} else {
sbStr.append(chars[i]);
}
}
ftpPath = sbStr.toString();
if (ftpPath.indexOf('/') == -1) {
// 只有一层目录
ftpClient.changeWorkingDirectory(new String(ftpPath.getBytes(), "iso-8859-1"));
} else {
// 多层目录循环创建
String[] paths = ftpPath.split("/");
for (int i = 0; i < paths.length; i++) {
ftpClient.changeWorkingDirectory(new String(paths[i].getBytes(), "iso-8859-1"));
}
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 循环创建目录,并且创建完目录后,设置工作目录为当前创建的目录下
* @param ftpPath 需要创建的目录
* @return
*/
public boolean mkDir(String ftpPath) {
if (!ftpClient.isConnected()) {
return false;
}
try {
// 将路径中的斜杠统一
char[] chars = ftpPath.toCharArray();
StringBuffer sbStr = new StringBuffer(256);
for (int i = 0; i < chars.length; i++) {
if ('\\' == chars[i]) {
sbStr.append('/');
} else {
sbStr.append(chars[i]);
}
}
ftpPath = sbStr.toString();
System.out.println("ftpPath:" + ftpPath);
if (ftpPath.indexOf('/') == -1) {
// 只有一层目录
ftpClient.makeDirectory(new String(ftpPath.getBytes(), "iso-8859-1"));
ftpClient.changeWorkingDirectory(new String(ftpPath.getBytes(), "iso-8859-1"));
} else {
// 多层目录循环创建
String[] paths = ftpPath.split("/");
for (int i = 0; i < paths.length; i++) {
ftpClient.makeDirectory(new String(paths[i].getBytes(), "iso-8859-1"));
ftpClient.changeWorkingDirectory(new String(paths[i].getBytes(), "iso-8859-1"));
}
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 上传文件到FTP服务器
* @param localDirectoryAndFileName 本地文件目录和文件名
* @param ftpFileName 上传到服务器的文件名
* @param ftpDirectory FTP目录如:/path1/pathb2/,如果目录不存在会自动创建目录
* @return
*/
public boolean upload(InputStream fileStream , String ftpFileName, String ftpDirectory) {
if (!ftpClient.isConnected()) {
return false;
}
boolean flag = false;
if (ftpClient != null) {
/* File srcFile = new File(localDirectoryAndFileName);
FileInputStream fis = null;*/
try {
/* fis = new FileInputStream(srcFile);*/
// 创建目录
this.mkDir(ftpDirectory);
ftpClient.setBufferSize(100000);
ftpClient.setControlEncoding("UTF-8");
// 设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
// 上传
flag = ftpClient.storeFile(new String(ftpFileName.getBytes(), "iso-8859-1"), fileStream);
} catch (Exception e) {
this.close();
e.printStackTrace();
return false;
}
}
// System.out.println("上传文件成功,本地文件名: " + localDirectoryAndFileName + ",上传到目录:" + ftpDirectory + "/" + ftpFileName);
return flag;
}
/**
* 从FTP服务器上下载文件
* @param ftpDirectoryAndFileName ftp服务器文件路径,以/dir形式开始
* @param localDirectoryAndFileName 保存到本地的目录
* @return
*/
public boolean get(String ftpDirectoryAndFileName, String localDirectoryAndFileName) {
if (!ftpClient.isConnected()) {
return false;
}
ftpClient.enterLocalPassiveMode(); // Use passive mode as default
try {
// 将路径中的斜杠统一
char[] chars = ftpDirectoryAndFileName.toCharArray();
StringBuffer sbStr = new StringBuffer(256);
for (int i = 0; i < chars.length; i++) {
if ('\\' == chars[i]) {
sbStr.append('/');
} else {
sbStr.append(chars[i]);
}
}
ftpDirectoryAndFileName = sbStr.toString();
String filePath = ftpDirectoryAndFileName.substring(0, ftpDirectoryAndFileName.lastIndexOf("/"));
String fileName = ftpDirectoryAndFileName.substring(ftpDirectoryAndFileName.lastIndexOf("/") + 1);
this.changeDir(filePath);
ftpClient.retrieveFile(new String(fileName.getBytes(), "iso-8859-1"),
new FileOutputStream(localDirectoryAndFileName)); // download
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 返回FTP目录下的文件列表
* @param pathName
* @return
*/
public String[] getFileNameList(String pathName) {
try {
return ftpClient.listNames(pathName);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 删除FTP上的文件
* @param ftpDirAndFileName 路径开头不能加/,比如应该是test/filename1
* @return
*/
public boolean deleteFile(String ftpDirAndFileName) {
if (!ftpClient.isConnected()) {
return false;
}
try {
return ftpClient.deleteFile(ftpDirAndFileName);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 删除FTP目录
* @param ftpDirectory
* @return
*/
public boolean deleteDirectory(String ftpDirectory) {
if (!ftpClient.isConnected()) {
return false;
}
try {
return ftpClient.removeDirectory(ftpDirectory);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 关闭链接
*/
public void close() {
try {
if (ftpClient != null && ftpClient.isConnected()) {
ftpClient.disconnect();
}
// System.out.println("成功关闭连接,服务器ip:" + this.server + ", 端口:" + this.port);
} catch (Exception e) {
e.printStackTrace();
}
}
public FTPClient getFtpClient() {
return ftpClient;
}
public void setFtpClient(FTPClient ftpClient) {
this.ftpClient = ftpClient;
}
}
@RequestMapping(value = “/uploadFiles”)
@ResponseBody
public List uploadFiles(MultipartHttpServletRequest multipartRequest,HttpServletRequest request, Model model) {
List attachmentList = new ArrayList();
InputStream appExcelStream = null;
try {
String fileSource = request.getParameter(“fileSource”);
String refType = request.getParameter(“refType”);
if(fileSource == null ){
fileSource = “platform”;
}
for (Iterator it = multipartRequest.getFileNames(); it.hasNext();) {
String key = (String) it.next();
MultipartFile imgFile = multipartRequest.getFile(key);
if (imgFile.getOriginalFilename().length() > 0) {
InputStream fileStream = imgFile.getInputStream();
String fileName = imgFile.getOriginalFilename();
String[] nameAndSuffix = CommonUtils.getFileNameAndSuffix(fileName);
String dateStr = new SimpleDateFormat(“yyyy/MM/dd”).format(new Date());
String id = IdGenerator.uuid();
// 存到数据库的路径
String attachmentPath = “eplatform/attachments/” + fileSource + File.separator +dateStr + File.separator;
FtpUtils ftpUtil=new FtpUtils();
if(ftpUtil.open()) {
ftpUtil.uploadFile(attachmentPath, id + “.” + nameAndSuffix[1], fileStream);
fileStream.close();
ftpUtil.close();
}
Attachment attachment = new Attachment();
attachment.setAttachmentId(id);
attachment.setName(fileName);
attachment.setDescription(“”);
//attachment.setType(imgFile.getContentType().substring(imgFile.getContentType().indexOf(“/”)+1, imgFile.getContentType().length()));
attachment.setType(fileName.substring(fileName.lastIndexOf(“.”)));
attachment.setTime(new Date());
attachment.setFileSize(imgFile.getSize()+”“);
attachment.setPath(attachmentPath + id + “.” + nameAndSuffix[1]);
attachment.setRefId(“”);
attachment.setSourse(“esgrid”);
attachment.setIsCreatedSwf(“0”);
if(refType != null && !”“.equals(refType)){
attachment.setRefType(refType);
}
attachmentList.add(attachment);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return attachmentList;
}
public void showPic(@PathVariable(“id”) String id,HttpServletRequest request, HttpServletResponse response){
try {
Attachment attachment = attachmentService.get(id);
// 权限验证
response.setContentType(“image/” + attachment.getType());
OutputStream os = response.getOutputStream();
FtpUtils ftp = new FtpUtils();
ftp.open();
FTPClient fc = ftp.getFtpClient();
fc.enterLocalPassiveMode();
fc.setFileType(FTPClient.BINARY_FILE_TYPE);
InputStream is = fc.retrieveFileStream(attachment.getPath());
FileCopyUtils.copy(is, os);
os.flush();
os.close();
ftp.close();
} catch (Exception e) {
e.printStackTrace();
}
}