springBoot整合ftp上传图片功能
知识点:
springBoot后端项目,接收前端框架传到的图片,把图片上传到ftp图片服务器上
注意:在上传的过程中可能回出现,可以创建文件夹,但是图片上传不了的问题;
尝试了网上的很多方法,最后将filename改为全路径上传成功
1. pom.xml中引入依赖的包
<!-- 加入上传文件组件 -->
<!-- https://mvnrepository.com/artifact/commons-net/commons-net -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.3</version>
</dependency>
2.ftp上传工具类FtpFileUtil.java
package com.hand.hand.util;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by nishuai on 2018/1/12.
*/
public class FtpFileUtil {
//ftp服务器ip地址
private static final String FTP_ADDRESS = "101.132.1.113";
//端口号
private static final int FTP_PORT = 21;
//用户名
private static final String FTP_USERNAME = "ftp";
//密码
private static final String FTP_PASSWORD = "123456";
//图片路径
private static final String FTP_BASEPATH = "/home/ftpadmin/health/images";
public static boolean uploadFile(String originFileName,InputStream input){
boolean success = false;
FTPClient ftp = new FTPClient();
ftp.setControlEncoding("GBK");
try {
int reply;
ftp.connect(FTP_ADDRESS, FTP_PORT);// 连接FTP服务器
ftp.login(FTP_USERNAME, FTP_PASSWORD);// 登录
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.makeDirectory(FTP_BASEPATH );
ftp.changeWorkingDirectory(FTP_BASEPATH );
ftp.storeFile(originFileName,input);
input.close();
ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
}
3.controller层接口 FtpFileUploadController.java
package com.hand.hand.controller;
import com.hand.hand.util.FtpFileUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by nishuai on 2017/12/26.
*/
@CrossOrigin
@Controller
public class FtpFileUploadController {
//ftp处理文件上传
@RequestMapping(value="/ftpuploadimg", method = RequestMethod.POST)
public @ResponseBody String uploadImg(@RequestParam("file") MultipartFile file,
HttpServletRequest request) throws IOException {
String fileName = file.getOriginalFilename();
InputStream inputStream=file.getInputStream();
String filePath=null;
Boolean flag=FtpFileUtil.uploadFile(fileName,inputStream);
if(flag==true){
System.out.println("ftp上传成功!");
filePath=fileName;
}
return filePath; //该路径图片名称,前端框架可用ngnix指定的路径+filePath,即可访问到ngnix图片服务器中的图片
}
}