首先引入ftp连接需要的jar包
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
需要更高版本的自己到maven去下载https://mvnrepository.com/artifact/commons-net/commons-nethttps://mvnrepository.com/artifact/commons-net/commons-net以get请求为例直接看
/**
* 对ftp进行短连接并进行文件输出
* 需要访问路径 ftp://ip:port/dddd/timg.jpg
*
* @param comment 文件路径地址 示例 /dddd/timg.jpg
* @param response
*/
@GetMapping("/imgUrl")
public void imgUrl(@RequestParam("comment") String comment
, HttpServletResponse response) {
//访问自定义ftp连接方法
FTPClient ftpClient = getFTPClient();
try {
//文件名称
String imageName = comment.substring(comment.lastIndexOf("/") + 1);
//文件夹路径
String fileName = comment.substring(0, comment.lastIndexOf("/"));
//进入到指定ftp文件夹
//ftpClient.changeWorkingDirectory(fileName);
//进入到指定ftp文件夹,未防止有中文路径添加处理
ftpClient.changeWorkingDirectory(new String(fileName.getBytes("GBK")
, "ISO-8859-1"));
//自定义一个名称,想叫什么名字就自己写我的叫Aa.xx,也可以直接叫文件本身名字,但记得
要做下中文名称处理
response.addHeader("Content-Disposition"
, "attachment;filename=Aa"
+ imageName.substring(imageName.lastIndexOf(".")));
OutputStream output = response.getOutputStream();
//写入输入流
// ftpClient.retrieveFile(imageName, output);
//写入输入流 ,未防止有中文文件名添加处理
ftpClient.retrieveFile(new String(imageName.getBytes("GBK")
, "ISO-8859-1")
, output);
response.setContentType("application/octet-stream");
//关闭ftp连接
ftpClient.logout();
ftpClient.disconnect();
//关闭输入流
output.flush();
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
因为项目需求中需要img的url路径,所以想要的路径为:http://ip:prot/path/imgUrl?comment=ftp的文件路径+文件名称(本项目文章为:http://ip:prot/path/imgUrl?comment=dddd/timg.jpg)
自定义ftp连接方法附上
config.url以及同级的ip、用户名及密码,我是直接配置到配置文件里,再注入容器时读取并最终直接注入到实现类
@Autowired
private FtpConfig config;
@Component
@ConfigurationProperties(prefix="allen.ftp")
public class FtpConfig {
private String url ;
private Integer port;
private String username ;
private String password ;
public String getUrl() { return url; }
public Integer getPort() {
return port;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public void setUrl(String url) {
this.url = url;
}
public void setPort(Integer port) {
this.port = port;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
}
springboot配置文件application.properties中添加连接信息
allen.ftp.url = 192.168.1.39
allen.ftp.port = 8096
allen.ftp.username = zl
allen.ftp.password = zhangyang123.
到此结束看效果: