FTPFileUtil_FTP文件上传 (spring boot)
import com.sinosoft.survey.api.SurveyConstant;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import java.io.IOException;
import java.io.InputStream;
public class FtpFileUtil {
/**
* FTP文件上传
* @param fileName 上传文件名称
* @param input
* @param ftpPath 上传路径 例:/upload/carInsuranceImage
* @return
*/
public static boolean uploadFile(String fileName,InputStream input,String ftpPath){
boolean success = false;
FTPClient ftp = new FTPClient();
ftp.setControlEncoding("GBK");
try {
int reply;
ftp.connect("127.0.0.1", "21");// 连接FTP服务器
ftp.login("ftp", "ftp");// 登录
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
boolean b = ftp.changeWorkingDirectory(ftpPath);//切换到上传路径 (路径是否存在)
if(!b){
String[] paths = ftpPath.substring(1).split("/");
StringBuffer sb = new StringBuffer();
for(String p : paths){
sb = sb.append("/"+p);
ftp.makeDirectory(sb.toString());//循环创建路径
}
ftp.changeWorkingDirectory(ftpPath);
}
ftp.storeFile(fileName,input);
input.close();
ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
}
service
public HashMap arriveScene( MultipartFile file, String orderNo, String registNo) throws IOException {
HashMap map = new HashMap();
Date date = new Date();
String originalFilename = file.getOriginalFilename();
int index = originalFilename.lastIndexOf(".");
String fileNameExt = originalFilename.substring(index+1);//文件扩展名
String fileName = registNo + "_"+ date.getTime()+ "." + fileNameExt;
InputStream inputStream=file.getInputStream();
Boolean flag=FtpFileUtil.uploadFile(fileName,inputStream,SurveyConstant.FTP_PATH_ARRIVESCENE);
if(flag==true){
map.put("msg","ok");
}else{
map.put("msg","error");
}
}
springboot
public HashMap arriveScene(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
String orderNo = request.getParameter("orderNo"); //和文件一起提交的其他参数
return mapService.arriveScene(file, orderNo, registNo);
}