- 添加pom依赖
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
- 编写服务配置
ftp:
url: 1.xxx.xxx.18
port: 21
user: ftp
password: ftp
remoteFilePath: /ftp/
- 编写ftp工具类FtpUtils.java
package cn.sh.ideal.utils;
import java.io.BufferedInputStream;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpProtocolException;
@Component
@Slf4j
public class FtpUtils implements InitializingBean{
private static FTPClient ftpClient = null;
@Value("${ftp.url}")
private String ftpUrl;
@Value("${ftp.port}")
private int ftpPort;
@Value("${ftp.user}")
private String ftpUser;
@Value("${ftp.password}")
private String ftpPassword;
private static String url;
private static int port;
private static String user;
private static String password;
@Override
public void afterPropertiesSet() throws Exception {
url=ftpUrl;
port=ftpPort;
user=ftpUser;
password=ftpPassword;
}
public static boolean uploadFTP(MultipartFile file, String filePath, String filename) {
boolean tmp = true;
tmp = uploadFile(file, filePath, filename);
return tmp;
}
public static boolean uploadFile(MultipartFile file, String filePath, String filename) {
TelnetOutputStream to = null;
BufferedInputStream inStream = null;
boolean success = false;
try {
if (file != null) {
connectFTP();
boolean tmp2 = ftpClient.changeWorkingDirectory(filePath.replace("\\", "/"));
log.info("FTP文件上传判断文件夹是否存在" + tmp2);
if (!tmp2) {
createDir(filePath.replace("\\", "/"));
boolean b = ftpClient.changeWorkingDirectory(filePath.replace("\\", "/"));
log.info("新建文件夹后,切换目录是否成功:{}",b);
}
inStream = new BufferedInputStream(file.getInputStream());
success = ftpClient.storeFile(filename, inStream);
if (success == true) {
return success;
}
}
return success;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (inStream != null) {
try {
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (to != null) {
try {
to.flush();
to.close();
} catch (IOException e) {
e.printStackTrace();
}
}
closeFTP();
}
}
public static boolean upload(MultipartFile file, String filePath, String fileName) throws FtpProtocolException {
boolean flag;
if(null != file){
connectFTP();
try {
flag = ftpClient.changeWorkingDirectory(filePath);
if(flag){
createDir(filePath.replace("\\", "/"));
boolean directory = ftpClient.changeWorkingDirectory(filePath.replace("\\", "/"));
log.info("创建目录后是否切换成功:{}", directory);
}
BufferedInputStream inputStream = new BufferedInputStream(file.getInputStream());
flag = ftpClient.storeFile(filePath, inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
public static void createDir(String dirname) {
try {
boolean b = ftpClient.makeDirectory(dirname);
log.info("是否在目标服务器上成功建立了文件夹: " + dirname + ","+b);
} catch (Exception e) {
log.info(e.getMessage());
}
}
private static void connectFTP() throws FtpProtocolException {
try {
ftpClient = new FTPClient();
ftpClient.connect(url, port);
int reply = ftpClient.getReplyCode();
if (FTPReply.isPositiveCompletion(reply)) {
ftpClient.setControlEncoding("UTF-8");
ftpClient.login(user, password);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.setBufferSize(1024 * 1024 * 10);
ftpClient.setDataTimeout(30 * 1000);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void closeFTP() {
try {
boolean reuslt = ftpClient.logout();
if (reuslt) {
System.out.println("成功退出服务器");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
System.out.println("关闭FTP服务器的连接异常!");
}
}
}
}
- 编写上传接口 FtpController.java
package cn.sh.ideal.controller;
import java.text.SimpleDateFormat;
import java.util.Date;
import cn.sh.ideal.utils.FtpUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequiredArgsConstructor
@Api(tags = "ftp文件上传")
@RequestMapping("/ftp")
@Slf4j
public class FtpController {
@Value("${ftp.remoteFilePath}")
private String remoteFilePath;
private static final Logger logger = LoggerFactory.getLogger(FtpController.class);
SimpleDateFormat sdf2=new SimpleDateFormat("yyyyMMdd");
@PostMapping("/upload")
@ResponseBody
@ApiOperation(value = "文件上传接口", notes = "文件上传接口")
public String upload(@RequestParam("file_data")MultipartFile file) {
String fileName = file.getOriginalFilename();
String suffix = (fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length())).toLowerCase();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmssSSS");
String dateStr = sdf.format(new Date());
int i = fileName.lastIndexOf(".");
String newFilename = dateStr + fileName.substring(i);
logger.info("newFileName:"+newFilename);
String fileNewPath =sdf2.format(new Date());
String pathStr = remoteFilePath + fileNewPath;
logger.info("文件上传文件夹路径"+pathStr);
boolean tmp = false;
try{
tmp = FtpUtils.uploadFTP(file, pathStr, newFilename);
logger.info("文件上传结果:"+tmp);
}catch (Exception e){
e.printStackTrace();
return new String("文件上传异常");
}
if(!tmp){
return new String("文件上传失败");
}
String filepath =pathStr+newFilename;
logger.info("返回到页面的文件FTP路径"+filepath);
return filepath;
}
}