现在阿里云有很好的图片管理OSS,但是对于很多企业还是有自己的服务器来管理图片,这些图片不是很多但是又是非常必要的。网上常常有各种上传的示例,但是非常遗憾,很多都是错误或者不完整的,趁着这两天有时间,我整理了下,希望能帮助到使用的人。直接贴代码:
package com.alice.common.utils.upload;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
public class FtpUtil {
private String ftpPath = "http://xxx.xx.com" ;
private String ftpName = "ftpname" ;
private String ftpPwd = "123456" ;
private String ftpServerIp = "xxx.xx.xx.xx" ;
public String saveInFTP( String folderName,String fileName,MultipartFile file){
String imgUrl = null ;
FTPClient ftpClient = new FTPClient() ; //创建图片上传对象
InputStream fis = null ;
try{
if( folderName != null && !StringUtils.isEmpty(folderName)
&& fileName != null && !StringUtils.isEmpty(fileName) ){
ftpClient.connect(this.ftpServerIp) ;
if( ftpClient.login(this.ftpName, this.ftpPwd) ){
String[] array = folderName.split("/") ;
//循环创建目录
if( array != null && array.length > 0 ){
String tmp = "" ;
for( String str:array ){
if( !StringUtils.isEmpty(str) ){
tmp = tmp + "/" + str ;
ftpClient.makeDirectory(tmp) ;
}
}
}
if( ftpClient.changeWorkingDirectory( folderName ) ){
ftpClient.setBufferSize(1021);
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
fis = file.getInputStream() ;
boolean flag = ftpClient.storeFile(fileName, fis);
if( flag ){
imgUrl = this.ftpPath + folderName + fileName ;
}
}
}
}
}
catch( Exception e ){
e.printStackTrace();
}
finally{
try{
IOUtils.closeQuietly(fis);
ftpClient.disconnect();
}
catch( IOException e ){
e.printStackTrace();
}
}
return imgUrl ;
}
//删除文件目录
public boolean delFolderString folderName){
boolean flag = false ;
FTPClient ftpClient = new FTPClient() ;
InputStream fis = null ;
try{
if( folderName != null && !StringUtils.isEmpty(folderName)){
ftpClient.connect(this.ftpServerIp) ;
if( ftpClient.login(this.ftpName, this.ftpPwd) ){
flag = ftpClient.removeDirectory(folderName) ;
}
}
}
catch( Exception e ){
e.printStackTrace();
}
finally{
try{
IOUtils.closeQuietly(fis);
ftpClient.disconnect();
}
catch( IOException e ){
e.printStackTrace();
}
}
return flag ;
}
//删除文件
public boolean delFile(String file){
boolean flag = false ;
FTPClient ftpClient = new FTPClient() ;
InputStream fis = null ;
try{
if( file != null && !StringUtils.isEmpty(file)){
ftpClient.connect(this.ftpServerIp) ;
if( ftpClient.login(this.ftpName, this.ftpPwd) ){
flag = ftpClient.deleteFile(file) ;
}
}
}
catch( Exception e ){
e.printStackTrace();
}
finally{
try{
IOUtils.closeQuietly(fis);
ftpClient.disconnect();
}
catch( IOException e ){
e.printStackTrace();
}
}
return flag ;
}
}