package com.zjqy.qbcs.common;
import com.zjqy.qbcs.util.DownloadFile;
import com.zjqy.qbcs.util.FtpUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.MalformedURLException;
import java.util.UUID;
@RestController
@Service
public class FtpUtils2 {
private final Logger logger = LoggerFactory.getLogger(FtpUtils.class);
//ftp服务器地址
@Value("${ftp.ip}")
private String hostname;
@Value("${ftp.port}")
private int port;
@Value("${ftp.username}")
private String username;
@Value("${ftp.password}")
private String password;
@Value("${server.port}")
private int bdPort;
@Value("${server.servlet.context-path}")
private String contextPath;
/**
* 本地临时目录 需要 定期清空
*/
@Value("${benDi.localDirectory}")
private String localDirectory;
@Value("${fileUpload.file_url_head}")
private String file_url_head;
@Value("${fileUpload.home_pic_url_directory}")
private String home_pic_url_directory;
@Value("${fileUpload.goods_pic_url_directory}")
private String goods_pic_url_directory;
@Value("${fileUpload.report_url_directory}")
private String report_url_directory;
@Value("${fileUpload.train_video_directory}")
private String train_video_directory;
@Value("${fileUpload.file_download_directory}")
private String file_download_directory;
@Value("${fileUpload.model_default_img}")
private String model_default_img;
@Value("${fileUpload.tool_default_img}")
private String tool_default_img;
@Value("${fileUpload.train_default_img}")
private String train_default_img;
@Value("${fileUpload.report_default_img}")
private String report_default_img;
public FTPClient ftpClient = null;
/**
* 初始化ftp服务器
*/
public void initFtpClient() {
ftpClient = new FTPClient();
ftpClient.setControlEncoding("utf-8");
try {
//System.out.println("connecting...ftp服务器:"+this.hostname+":"+this.port);
ftpClient.connect(hostname, port); //连接ftp服务器
ftpClient.login(username, password); //登录ftp服务器
int replyCode = ftpClient.getReplyCode(); //是否成功登录服务器
logger.trace(String.valueOf(replyCode));
if (!FTPReply.isPositiveCompletion(replyCode)) {
logger.trace("connect failed...ftp服务器:" + this.hostname + ":" + this.port);
}
logger.trace("connect successfu...ftp服务器:" + this.hostname + ":" + this.port);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 文件上传
* @param file 文件
* @param type 目录类型
* @return
*/
@RequestMapping("/uploadFileAll")
public String uploadFileAll(MultipartFile file,int type) {
try {
if (file != null) {
String ftpFilePath = getType(type);
String originalFilename = file.getOriginalFilename();//文件名字
String suffix = originalFilename.substring(originalFilename.lastIndexOf('.'));
String newFileName = UUID.randomUUID() + suffix;
File a=new File(localDirectory);
if (a.exists()) {
a.mkdirs();
}
File fil = new File(localDirectory + newFileName);
if (fil.exists()) {
fil.mkdirs();
}
file.transferTo(fil);
boolean b = uploadToFtp(fil, ftpFilePath);
if (b) {
System.out.println("上传ftp成功");
//删除本地的
fil.delete();
}
StringBuffer stringBuffer = new StringBuffer();
// stringBuffer.append("localhost:");
// stringBuffer.append(bdPort);
// stringBuffer.append(contextPath);
stringBuffer.append("/downloadFileAllAndQuery");
stringBuffer.append("?type=");
stringBuffer.append(type);
stringBuffer.append("&fileName=");
stringBuffer.append(newFileName);
System.err.println("接口地址为:" + stringBuffer.toString());
return stringBuffer.toString();
} else {
System.out.println("文件是空的");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 文件下载
* @param type ftp文件所在目录位置
* @param fileName 文件名称
* @return
*/
@RequestMapping("/downloadFileAllAndQuery")
public ResponseEntity<InputStreamResource> downloadFileAllAndQuery(int type, String fileName) {
String path = null;
String f = null;
try {
String ftpFilePath=getType(type);
initFtpClient();
ftpClient.changeWorkingDirectory(ftpFilePath);
ftpClient.enterLocalPassiveMode();
if (ftpClient != null) {
FTPFile[] files = ftpClient.listFiles();
for (FTPFile file : files) {
f = new String(file.getName().getBytes("iso-8859-1"), "utf-8");//防止乱码
System.out.println(f);
if (f.equals(fileName)) { //aa44ce45-0fc3-40c7-ac2c-23b5568fd7f9.mp4 7961ad9c-78e8-463a-8619-03f05fdf9622.jpeg
path = localDirectory + File.separatorChar + f;
File localFile = new File(path);
OutputStream os = new FileOutputStream(localFile);
ftpClient.retrieveFile(f, os);
os.close();
ftpClient.logout();
break;
}
}
DownloadFile downloadFile = new DownloadFile();
return downloadFile.downloadFile(path, f);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private String getType(int type) {
String ftpFilePath=null;
if (type==1){
ftpFilePath=file_url_head;
}else if (type==2){
ftpFilePath=home_pic_url_directory;
}else if (type==3){
ftpFilePath=goods_pic_url_directory;
}else if (type==4){
ftpFilePath=report_url_directory;
}else if (type==5){
ftpFilePath=train_video_directory;
}else if (type==6){
ftpFilePath=file_download_directory;
}else if (type==7){
ftpFilePath=model_default_img;
}else if (type==8){
ftpFilePath=tool_default_img;
}else if (type==9){
ftpFilePath=train_default_img;
}else if (type==10){
ftpFilePath=report_default_img;
}
return ftpFilePath;
}
private boolean uploadToFtp(File file,String ftpFilePath){
try {
initFtpClient();
ftpClient.changeWorkingDirectory(ftpFilePath);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
ftpClient.storeFile(file.getName(), new FileInputStream(file));
System.out.println(file.getName());
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
}
让类可以读取的数据