話不多說直接上代碼
package com.springboot.demo.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.PrintCommandListener;
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.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;
import java.io.*;
import java.net.SocketException;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
public class FtpUtil {
private final static Log logger = LogFactory.getLog(FtpUtil.class);
private static String LOCAL_CHARSET = "UTF-8";
// FTP協定裡面,規定檔案名編碼為iso-8859-1
private static String SERVER_CHARSET = "ISO-8859-1";
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static Date TODAY_TIME = new Date();
/**
* @return
* @Author Mr伍
* @Description //TODO
* @Date 2020/4/1
* @Param
**/
public static FTPClient getFTPClient(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort) {
FTPClient ftpClient = new FTPClient();
try {
ftpClient = new FTPClient();
ftpClient.connect(ftpHost, ftpPort); // 連接配接FTP伺服器
ftpClient.login(ftpUserName, ftpPassword); // 登陸FTP伺服器
ftpClient.setControlEncoding("UTF-8"); // 中文支援
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
logger.info("未連接配接到FTP,使用者名或密碼錯誤。");
ftpClient.disconnect();
} else {
logger.info("FTP連接配接成功。");
}
} catch (SocketException e) {
e.printStackTrace();
logger.info("FTP的IP位址可能錯誤,請正确配置。");
} catch (IOException e) {
e.printStackTrace();
logger.info("FTP的端口錯誤,請正确配置。");
}
return ftpClient;
}
//判斷ftp的目标檔案下是否有此檔案
public static boolean isExsits(String ftpPath, String fileName, FTPClient ftpx) {
try {
FTPFile[] files = ftpx.listFiles(ftpPath);
if (files != null && files.length > 0) {
System.out.println("files size:" + files[0].getSize());
for (FTPFile file : files
) {
String st = new String(file.getName().getBytes(LOCAL_CHARSET), SERVER_CHARSET);
String st1 = new String(st.getBytes(SERVER_CHARSET), LOCAL_CHARSET);
if (st1.equals(fileName)) {
return true;
}
}
return false;
} else {
return false;
}
} catch (Exception e) {
logger.error("擷取檔案清單失敗" + e.getMessage() + e.getClass().getName());
return false;
//e.printStackTrace();
}
}
/**
* 從FTP伺服器下載下傳檔案
* @param ftpHost FTP IP位址
* @param ftpUserName FTP 使用者名
* @param ftpPassword FTP使用者名密碼
* @param ftpPort FTP端口
* @param ftpPath FTP伺服器中檔案所在路徑 格式: ftptest/aa
* @param localPath 下載下傳到本地的位置 格式:H:/download
* @param fileName FTP伺服器上要下載下傳的檔案名稱
* @param targetFileName 本地上要的檔案名稱
*/
public static String downloadFtpFile(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort, String ftpPath, String localPath, String fileName, String targetFileName) {
FTPClient ftpClient = null;
try {
ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(
"OPTS UTF8", "ON"))) {// 開啟伺服器對UTF-8的支援,如果伺服器支援就用UTF-8編碼,否則就使用本地編碼(GBK).
LOCAL_CHARSET = "UTF-8";
}
if(!ftpClient.changeWorkingDirectory(ftpPath)){
logger.error("檔案夾路徑不對");
return "檔案夾路徑不對";
};
boolean flag = isExsits(ftpPath, fileName, ftpClient);
if (!flag) {
logger.error("檔案:" + fileName + " 不存在");
return "檔案:" + fileName + " 不存在";
}
String f_ame = new String(fileName.getBytes("GBK"), FTP.DEFAULT_CONTROL_ENCODING); //編碼檔案格式,解決中文檔案名
File localFile = new File(localPath + File.separatorChar + targetFileName);
OutputStream os = new FileOutputStream(localFile);
ftpClient.retrieveFile(f_ame, os);
os.close();
ftpClient.logout();
File file=new File(System.getProperty("java.io.tmpdir")+targetFileName);
FileInputStream inputFile = new FileInputStream(file);
byte[] buffer = new byte[(int)file.length()];
inputFile.read(buffer);
inputFile.close();
if(file.exists()){
file.delete();//删除檔案
}
return new BASE64Encoder().encode(buffer);
// return "下載下傳成功";
} catch (FileNotFoundException e) {
logger.error("沒有找到" + ftpPath + "檔案");
e.printStackTrace();
} catch (SocketException e) {
logger.error("連接配接FTP失敗.");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
logger.error("檔案讀取錯誤。");
e.printStackTrace();
}
return "下載下傳失敗";
}
public static String uploadFile(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort, String base64, String fileName) {
String today = new SimpleDateFormat("yyyyMMdd").format(new Date());
String path_wl =today;
MultipartFile file = Base64StrToImage.base64MutipartFile(base64);
String name = fileName;
System.err.println(name);
FTPClient ftp = new FTPClient();
try {
//設定編碼
ftp.setControlEncoding("utf-8");
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
//連接配接ftp伺服器
ftp.connect(ftpHost, ftpPort);
//響應碼
if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
ftp.disconnect();
}
//登入ftp
boolean login = ftp.login(ftpUserName, ftpPassword);
if (!login) {
return "ftp伺服器登入失敗。請重新開始";
}
//設定為二進制格式
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
// System.out.println("已連接配接"+ftp.isConnected());//檢視ftp是否已連接配接
logger.debug("ftp連接配接狀态" + ftp.isConnected());
if (!ftp.changeWorkingDirectory(path_wl)) {
boolean b = ftp.makeDirectory(path_wl);
if (b) {
ftp.changeWorkingDirectory(path_wl);
ftp.appendFile(name, file.getInputStream());
}
} else {
ftp.appendFile(name, file.getInputStream());
}
logger.debug("寫入成功==========");
} catch (IOException e) {
logger.error("檔案儲存失敗:" + e.getMessage());
e.printStackTrace();
return "檔案儲存失敗";
} finally {
try {
ftp.logout();
ftp.disconnect();
if (ftp.isConnected()) {
ftp.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return "檔案儲存成功";
}
public static void main(String[] args) {
String ftpHost = "localhost";
String ftpUserName = "syftp";
String ftpPassword = "1";
int ftpPort = 21;
String ftpPath = "\\20200403\\";
String fileName = "房産檔案索引表.jpeg";
//上傳一個檔案
try {
File f = new File("E:\\zyb.png");
FileInputStream inputFile = new FileInputStream(f);
byte[] buffer = new byte[(int)f.length()];
inputFile.read(buffer);
inputFile.close();
String str= new BASE64Encoder().encode(buffer);
str="data:image/jpeg;base64,"+str;
String flag = FtpUtil.uploadFile(ftpHost, ftpUserName, ftpPassword, ftpPort,str,fileName);
// System.err.println(flag);
String tmpPath = System.getProperty("java.io.tmpdir");
System.out.println(tmpPath);//本機臨時檔案夾 C:\Users\DELL\AppData\Local\Temp\
//檔案下載下傳...輸出圖檔base64字元
String resoult = FtpUtil.downloadFtpFile(ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, tmpPath, fileName, "tempFile.jpeg");
System.err.println(resoult);
//TODO 檔案是pdf時使用字元串轉pdf的util
// Base64AndPdf.Base64toPdffile("data:application/pdf;base64,"+resoult,"E:\\a13.pdf");
//TODO 檔案是圖檔時使用圖檔的util轉
MultipartFile multipartFile=Base64StrToImage.base64MutipartFile("data:application/pdf;base64,"+resoult);
multipartFile.transferTo(Paths.get("E:\\tupian.pdf"));
System.err.println("成功");
} catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
}
}
此處自己了解,看自己的上傳的檔案帶不帶字首
package com.springboot.demo.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
public class Base64StrToImage {
Logger logger = LoggerFactory.getLogger(Base64StrToImage.class);
public static MultipartFile base64MutipartFileNew(String imgStr){
try {
String [] baseStr = imgStr.split(",");
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] b = new byte[0];
if(baseStr.length==2){
b = base64Decoder.decodeBuffer(baseStr[1]);
for(int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
return new BASE64DecodedMultipartFile(b,baseStr[0]) ;
}else {
b = base64Decoder.decodeBuffer(imgStr);
for(int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
return new BASE64DecodedMultipartFile(b,"data:application/pdf;base64,") ;
}
}catch (Exception e){
e.printStackTrace();
return null;
}
}
}
util2
package com.will.doing.util;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import java.io.*;
import java.net.MalformedURLException;
/**
* @Author Mr伍
* @Description //TODO
* @Date 2020/8/18
* @Param
* @return
**/
public class FtpUtils {
//ftp伺服器位址
private String hostname;
//ftp伺服器端口号預設為21
private Integer port;
//ftp登入賬号
private String username;
//ftp登入密碼
private String password;
private FTPClient ftpClient = null;
public FTPClient getFtpClient(boolean init) {
if (init) {
boolean b = initFtpClient();
if (!b) {
System.err.println("ftp伺服器連接配接失敗");
return null;
}
}
return ftpClient;
}
public FtpUtils(String hostname, Integer port, String username, String password) {
this.hostname = hostname;
this.port = port;
this.username = username;
this.password = password;
}
/**
* 初始化ftp伺服器
*/
private boolean initFtpClient() {
boolean flag = false;
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(); //是否成功登入伺服器
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("connect failed...ftp伺服器:" + this.hostname + ":" + this.port);
flag = false;
} else {
System.out.println("connect successfu...ftp伺服器:" + this.hostname + ":" + this.port);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
flag = true;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return flag;
}
/**
* 上傳檔案
*
* @param pathname ftp服務儲存位址
* @param fileName 上傳到ftp的檔案名
* @param originfilename 待上傳檔案的名稱(絕對位址) *
* @return
*/
public boolean uploadFile(String pathname, String fileName, String originfilename) {
boolean flag = false;
InputStream in = null;
try {
System.out.println("開始上傳檔案");
in = new FileInputStream(new File(originfilename));
boolean b = initFtpClient();
if (!b) {
System.err.println("ftp伺服器連接配接失敗");
return false;
}
ftpClient.makeDirectory(pathname);
ftpClient.changeWorkingDirectory(pathname);
ftpClient.storeFile(fileName, in);
flag = true;
System.out.println("上傳檔案成功");
} catch (Exception e) {
System.out.println("上傳檔案失敗");
e.printStackTrace();
} finally {
try {
ftpClient.logout();
} catch (IOException e) {
e.printStackTrace();
}
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return flag;
}
/**
* 上傳檔案
*
* @param pathname ftp服務儲存位址
* @param fileName 上傳到ftp的檔案名
* @param in 輸入檔案流
* @return
*/
public boolean uploadFile(String pathname, String fileName, InputStream in) {
boolean flag = false;
try {
System.out.println("開始上傳檔案");
boolean b = initFtpClient();
if (!b) {
return false;
}
ftpClient.makeDirectory(pathname);
ftpClient.changeWorkingDirectory(pathname);
ftpClient.storeFile(fileName, in);
flag = true;
System.out.println("上傳檔案成功");
} catch (Exception e) {
System.out.println("上傳檔案失敗");
e.printStackTrace();
} finally {
try {
ftpClient.logout();
} catch (IOException e) {
e.printStackTrace();
}
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return flag;
}
//改變目錄路徑
public boolean changeWorkingDirectory(String directory) {
boolean flag = false;
try {
flag = ftpClient.changeWorkingDirectory(directory);
if (flag) {
System.out.println("進入檔案夾" + directory + " 成功!");
} else {
System.out.println("進入檔案夾" + directory + " 失敗!開始建立檔案夾");
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return flag;
}
//建立多層目錄檔案,如果有ftp伺服器已存在該檔案,則不建立,如果無,則建立
public boolean CreateDirecroty(String remote) throws IOException {
boolean success = true;
String directory = remote + "/";
// 如果遠端目錄不存在,則遞歸建立遠端伺服器目錄
if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(new String(directory))) {
int start = 0;
int end = 0;
if (directory.startsWith("/")) {
start = 1;
} else {
start = 0;
}
end = directory.indexOf("/", start);
String path = "";
String paths = "";
while (true) {
String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
path = path + "/" + subDirectory;
if (!existFile(path)) {
if (makeDirectory(subDirectory)) {
changeWorkingDirectory(subDirectory);
} else {
System.out.println("建立目錄[" + subDirectory + "]失敗");
changeWorkingDirectory(subDirectory);
}
} else {
changeWorkingDirectory(subDirectory);
}
paths = paths + "/" + subDirectory;
start = end + 1;
end = directory.indexOf("/", start);
// 檢查所有目錄是否建立完畢
if (end <= start) {
break;
}
}
}
return success;
}
//判斷ftp伺服器檔案是否存在
public boolean existFile(String path) throws IOException {
boolean flag = false;
FTPFile[] ftpFileArr = ftpClient.listFiles(path);
if (ftpFileArr.length > 0) {
flag = true;
}
return flag;
}
//建立目錄
public boolean makeDirectory(String dir) {
boolean flag = true;
try {
flag = ftpClient.makeDirectory(dir);
if (flag) {
System.out.println("建立檔案夾" + dir + " 成功!");
} else {
System.out.println("建立檔案夾" + dir + " 失敗!");
}
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/**
* 下載下傳檔案 *
*
* @param pathname FTP伺服器檔案目錄 *
* @param filename 檔案名稱 *
* @param localpath 下載下傳後的檔案路徑 *
* @return
*/
public boolean downloadFile(String pathname, String filename, String localpath) {
boolean flag = false;
OutputStream os = null;
try {
System.out.println("開始下載下傳檔案");
boolean b = initFtpClient();
if (!b) {
System.err.println("連接配接ftp伺服器失敗");
return false;
}
//切換FTP目錄
ftpClient.changeWorkingDirectory(pathname);
FTPFile[] ftpFiles = ftpClient.listFiles();
for (FTPFile file : ftpFiles) {
if (filename.equalsIgnoreCase(file.getName())) {
File localFile = new File(localpath + "/" + file.getName());
os = new FileOutputStream(localFile);
ftpClient.retrieveFile(file.getName(), os);
os.close();
}
}
ftpClient.logout();
flag = true;
System.out.println("下載下傳檔案成功");
} catch (Exception e) {
System.out.println("下載下傳檔案失敗");
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return flag;
}
public ByteArrayOutputStream getByteArrayOutputStream(String pathname, String filename) {
ByteArrayOutputStream os = null;
try {
System.out.println("開始下載下傳檔案");
boolean b = initFtpClient();
if (!b) {
System.err.println("連接配接ftp伺服器失敗");
}
//切換FTP目錄
ftpClient.changeWorkingDirectory(pathname);
FTPFile[] ftpFiles = ftpClient.listFiles();
for (FTPFile file : ftpFiles) {
if (filename.equalsIgnoreCase(file.getName())) {
os = new ByteArrayOutputStream();
boolean b1 = ftpClient.retrieveFile(file.getName(), os);
if(b1){
break;
}else{
os = null;
}
}
}
ftpClient.logout();
System.out.println("下載下傳檔案成功");
} catch (Exception e) {
System.out.println("下載下傳檔案失敗");
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return os;
}
/*
//測試-導入本地檔案
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream("C:\ins.pdf");
fileOutputStream.write(byteArrayOutputStream.toByteArray());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
*/
/**
* 删除檔案 *
*
* @param pathname FTP伺服器儲存目錄 *
* @param filename 要删除的檔案名稱 *
* @return
*/
public boolean deleteFile(String pathname, String filename) {
boolean flag = false;
try {
System.out.println("開始删除檔案");
boolean b = initFtpClient();
if (!b) {
System.err.println("連接配接ftp伺服器失敗");
}
//切換FTP目錄
ftpClient.changeWorkingDirectory(pathname);
ftpClient.dele(filename);
ftpClient.logout();
flag = true;
System.out.println("删除檔案成功");
} catch (Exception e) {
System.out.println("删除檔案失敗");
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return flag;
}
}
擴充 ByteArrayOutputStream 轉base64
try(ByteArrayOutputStream os = new ByteArrayOutputStream()) {
docxExporter.setExporterOutput(new SimpleOutputStreamExporterOutput(os));
docxExporter.exportReport();
docxExporter.setExporterOutput(new SimpleOutputStreamExporterOutput(os));
docxExporter.exportReport();
FileOutputStream fileOutputStream = new FileOutputStream("D:/pri.pdf");
fileOutputStream.write(os.toByteArray());
DataOutputStream dos = new DataOutputStream(os);
//boolean 1位
dos.writeBoolean(true);
// int 32位 4位元組
dos.writeInt(2);
// float 32位 32位元組
dos.writeFloat(1.234354f);
byte[] bArray = os.toByteArray();
System.out.println("共"+bArray.length+"位元組");
for (int i = 0; i < bArray.length; ++i){
System.out.println(bArray[i]+" ");
}
String base64=new BASE64Encoder().encode(bArray);
Base64AndPdf.base64StringToPDF(base64,"D:/pri111.pdf");
MultipartFile multipartFile=new BASE64DecodedMultipartFile(bArray,"data:application/pdf;base64,") ;
multipartFile.transferTo(new File("D:/pri222.pdf"));
}
ftp上傳-下載下傳檔案通用工具類,已實測,歡迎交流。