java实现ftp上传文件
程序员文章站
2022-06-02 14:17:32
...
一、java代码
(1)创建一个ftp工具类FTPUtil,连接ftp服务端,并上传文件。
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
/**
* Created by KABB on 2018/4/3.
*/
@Slf4j
public class FTPUtil {
//从配置文件读取ip,登录名和密码
private static String ftpIp = PropertiesUtil.getProperty("ftp.server.ip");
private static String ftpUser = PropertiesUtil.getProperty("ftp.user");
private static String ftpPass = PropertiesUtil.getProperty("ftp.pass");
public FTPUtil(String ip, int port, String user, String pwd){
this.ip = ip;
this.port = port;
this.user = user;
this.pwd = pwd;
}
public static boolean uploadFile(List<File> fileList) throws IOException {
FTPUtil ftpUtil = new FTPUtil(ftpIp,21,ftpUser,ftpPass);//端口是21
boolean result = ftpUtil.uploadFile("img",fileList);
return result;
}
private boolean uploadFile(String remotePath,List<File> fileList) throws IOException {
boolean uploaded = true;
FileInputStream fis = null;
//连接FTP服务器
if(connectServer(this.ip,this.port,this.user,this.pwd)){
try {
ftpClient.changeWorkingDirectory(remotePath);//更改工作目录
ftpClient.setBufferSize(1024);//设置缓冲区
ftpClient.setControlEncoding("UTF-8");
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);//文件类型设置成二进制类型,防止乱码
ftpClient.enterLocalPassiveMode();//打开本地被动模式
for(File fileItem : fileList){
fis = new FileInputStream(fileItem);
ftpClient.storeFile(fileItem.getName(),fis);//上传
}
} catch (IOException e) {
log.error("上传文件异常",e);
uploaded = false;
e.printStackTrace();
} finally {
fis.close();
ftpClient.disconnect();
}
}
return uploaded;
}
//连接ftp服务器
private boolean connectServer(String ip,int port,String user,String pwd){
boolean isSuccess = false;
ftpClient = new FTPClient();
try {
ftpClient.connect(ip,port);
isSuccess = ftpClient.login(user,pwd);
} catch (IOException e) {
log.error("连接FTP服务器异常",e);
}
return isSuccess;
}
private String ip;
private int port;
private String user;
private String pwd;
private FTPClient ftpClient;
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public FTPClient getFtpClient() {
return ftpClient;
}
public void setFtpClient(FTPClient ftpClient) {
this.ftpClient = ftpClient;
}
}
(2)建一个service,提供接口
import com.betterlife.service.IFileService;
import com.betterlife.util.FTPUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
/**
* Created by KABB on 2018/4/3.
*/
@Service("iFileService")
@Slf4j
public class FileServiceImpl implements IFileService {
public String upload(MultipartFile file,String path){
String fileName = file.getOriginalFilename();
String fileExtensionName = fileName.substring(fileName.lastIndexOf(".")+1);//得到扩展名
String uploadFileName = UUID.randomUUID().toString()+"."+fileExtensionName;//给上传的文件都随机生成一个文件名
log.info("开始上传文件,上传文件的文件名:{},上传的路径:{},新文件名:{}",fileName,path,uploadFileName);
File fileDir = new File(path);
if(!fileDir.exists()){
fileDir.setWritable(true);//为了使我们拥有tomcat下webapp写的权限
fileDir.mkdirs();
}
File targetFile = new File(path,uploadFileName);
try {
file.transferTo(targetFile);//文件已经上传到tomcat>webapp>ROOT>upload下了
FTPUtil.uploadFile(Lists.newArrayList(targetFile));//连接ftp并上传
targetFile.delete();
} catch (IOException e) {
log.error("上传文件异常",e);
return null;
}
return targetFile.getName();
}
}
(3)controller调用
@Controller
@RequestMapping("/manage/product")
public class ProductManageController {
@Autowired
private IUserService iUserService;
@Autowired
private IFileService iFileService;
@RequestMapping("upload.do")
@ResponseBody
public ServerResponse upload(@RequestParam(value = "upload_file",required = false) MultipartFile file,HttpServletRequest request){
String path = request.getSession().getServletContext().getRealPath("upload");
String targetFileName = iFileService.upload(file,path);
String url = PropertiesUtil.getProperty("ftp.server.http.prefix")+targetFileName;
Map fileMap = Maps.newHashMap();
fileMap.put("uri",targetFileName);
fileMap.put("url",url);
return ServerResponse.createBySuccess(fileMap);
}
}
二、效果:
jsp页面就不放了。(需要注意的是form表单enctype设置为multipart/form-data,以二进制上传)
先看ftp服务端,其中指定文件夹如下:
然后启动项目,打开浏览器,选择文件并上传。
返回的信息如下
ftp服务端,可以看到已经上传到了:
我们打开返回的url访问ftp服务:
到这里就ok了
上一篇: PS滤镜简单制作炫酷的线条效果