第一步连接FTP
第二部读取文件
第三步写入zip
第四步转化base64编码
话不多说上代码
package com.sinosoft.product.controller.sqltemplate;
import org.apache.commons.lang3.StringUtils;
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.apache.xerces.impl.dv.util.Base64;
import org.springframework.web.bind.annotation.GetMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.SocketException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @NAME: hzan
* @DATE: 2023/6/9
**/
public class down {
//脚本下载
@GetMapping("/file/down")
public Object fileDown(HttpServletResponse response, HttpServletRequest request) {
Map<String,Object> map=new HashMap<>();
map.put("status","0");
map.put("mes","失败");
FTPClient ftp = getFTPClient("127.0.0.1", 21, "appuser", "123456");
String base=null;
//定义ZIP流
ZipOutputStream zipOut =null;
BufferedInputStream bufferStream=null;
try {
ftp.enterLocalActiveMode();
ftp.setControlEncoding("UTF-8");
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
//远程文件所在ftp的路径
String dir = "/ReleaseFiles/File/Add/";
// 进入文件所在目录,注意编码格式,以能够正确识别中文目录
boolean cdStatus = ftp.changeWorkingDirectory(new String(dir.getBytes("UTF-8"), FTP.DEFAULT_CONTROL_ENCODING));
//定义压缩后的文件名称 注意:会在代码目录主动创建
File zipFile = new File("20230609.zip");
zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
//读取目录下的文件
FTPFile[] files = ftp.listFiles();
List<FTPFile> ftpFileList = Arrays.asList(files);
for (int i=0;i< ftpFileList.size();i++) {
//获取独立文件名
String file=ftpFileList.get(i).getName();
System.out.println("文件名称:" + file );
//读取文件 注意设置编码
InputStream input = ftp.retrieveFileStream(new String(file.getBytes("UTF-8"),FTP.DEFAULT_CONTROL_ENCODING));
if (input != null) {
/**将文件流写入zip文件中*/
byte[] bufferArea = new byte[1024 * 10];
bufferStream= new BufferedInputStream(input, 1024 * 10);
// 将当前文件作为一个zip实体写入压缩流,file代表压缩文件中的文件名称
zipOut.putNextEntry(new ZipEntry(file));
int length = 0;
while ((length = bufferStream.read(bufferArea, 0, 1024 * 10)) != -1) {
zipOut.write(bufferArea, 0, length);
}
// 需要注意的是缓冲流必须要关闭流,否则输出无效
bufferStream.close();
//关闭流
input.close();
//注意 切断ptf读取文件的连接
ftp.completePendingCommand();
}
}
// 压缩完成后,关闭压缩流
zipOut.close();
ftp.logout();
//断开ftp连接
ftp.disconnect();
//防止空文件
if(zipFile.length()>0){
base=file2Base64(zipFile);
if(StringUtils.isNotEmpty(base)){
base = "data:application/zip;base64,"+base;
map.put("status","1");
map.put("mes","成功");
map.put("base",base);
}
}
// 删除文件
zipFile.delete();
return map;
}catch (Exception e){
System.out.println("下载异常:"+e.getMessage());
e.printStackTrace();
}finally {
try {
if (zipOut != null) {
zipOut.close();
}
if(ftp!=null){
ftp.disconnect();
}
if(bufferStream!=null){
bufferStream.close();
}
} catch (IOException e) {
e.getMessage();
}
}
return map;
}
/**
* <p>将文件转成base64 字符串</p>
* @param file file对象
* @return
* @throws Exception
*/
public static String file2Base64(File file) {
if(file==null) {
return null;
}
String base64 = null;
FileInputStream fin = null;
try {
fin = new FileInputStream(file);
byte[] buff = new byte[fin.available()];
fin.read(buff);
base64 = Base64.encode(buff);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fin != null) {
try {
fin.close();
} catch (IOException e) {
System.out.println("file转base异常: "+e.getMessage());
}
}
}
return base64;
}
/**
*
* @param ftpAddress 连接FTP的地址
* @param ftpHost 端口号
* @param ftpUsername 用户名
* @param ftpPassword 密码
* @return
*/
public static FTPClient getFTPClient(String ftpAddress, int ftpHost, String ftpUsername, String ftpPassword) {
FTPClient ftpClient = new FTPClient();
try {
ftpClient.setDataTimeout(60000); //设置传输超时时间为60秒
ftpClient.setConnectTimeout(60000);
ftpClient.connect(ftpAddress, ftpHost);// 连接FTP服务器
ftpClient.login(ftpUsername, ftpPassword);// 登陆FTP服务器
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
System.out.println("未连接到FTP,用户名或密码错误");
ftpClient.disconnect();
} else {
System.out.println("FTP连接成功");
}
} catch (SocketException e) {
e.printStackTrace();
System.out.println("FTP的IP地址可能错误,请正确配置");
} catch (IOException e) {
e.printStackTrace();
System.out.println("FTP的端口错误,请正确配置");
}
return ftpClient;
}
}