Java通过ftp下载图片名称含有中文字符的图片
步骤:
1、先将ftp上的图片转为base64数据
2、下载至本地再转化为图片。
依赖的jar包
<!-- ftp -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.5</version>
</dependency>
config文件
#ftp
inter.host = 192.168.1.1
inter.port = 21
inter.username = ftp
inter.password = ftp
配置config
/*
配置类:配置ftp信息
*/
@Configuration
public class FtpConfigurer {
@Bean
public FtpHandler ftpHandler() throws IOException {
String path = System.getProperty("user.dir") + "/config/config.properties";
InputStream in= new FileInputStream(path);
Properties properties = new Properties();
properties.load(in);
String interHost = properties.getProperty("inter.host");
int interPort = Integer.valueOf(properties.getProperty("inter.port"));
String interUsername = properties.getProperty("inter.username");
String interPassword = properties.getProperty("inter.password");
return new FtpHandler(interHost, interPort, interUsername, interPassword);
}
}
ftp工具类
@Slf4j
public class FtpHandler {
private static String interHost;
private static int interPort;
private static String interUsername;
private static String interPassword;
private static FTPClient ftpInter;
private static boolean connFlag = false;
public FtpHandler(String interHost, int interPort, String interUsername, String interPassword) {
this.interHost = interHost;
this.interPort = interPort;
this.interUsername = interUsername;
this.interPassword = interPassword;
}
// 获取上传FTP的url
public String ftpUrl() {
return interHost;
}
// 获取FTP的用户名
public String interUsername() {
return interUsername;
}
// 获取ftp的密码
public String interPassword() {
return interPassword;
}
// 获取ftp的端口
public int interPort() {
return interPort;
}
// 连接ftp
public static boolean connect() {
String connecting = "";
try {
log.info("开始连接" + interHost);
connecting = interHost;
if (ftpInter == null) {
ftpInter = new FTPClient();
}
ftpInter.connect(interHost, interPort);
ftpInter.login(interUsername, interPassword);
log.info("连接" + interHost + "成功");
} catch (Exception e) {
log.error(e.getMessage());
log.error(connecting + "连接失败");
return false;
}
connFlag = true;
return true;
}
/**
* 下载图片
*
* @param ftpUrl 文件夹路径
* @param sfzh 图片路径
* @return
*/
public static String download(String ftpUrl, String sfzh) {
InputStream inputStream = null;
String re = null;
try {
/*
ftpClient.connect(ftp_ip,ftp_port);//ip地址,端口号
ftpClient.login(ftp_username, ftp_password);//账户,密码
*/
// 是否成功登录服务器
/*int reply = ftpInter.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpInter.disconnect();
}*/
// 跳转到指定目录
ftpInter.changeWorkingDirectory(ftpUrl);
// 5.遍历下载的目录
FTPFile[] fs = ftpInter.listFiles();
for (FTPFile ff : fs) {
// 解决中文乱码问题,两次解码
byte[] bytes = ff.getName().getBytes("iso-8859-1");
String fileName = new String(bytes, "gb2312");
if (sfzh.equals(fileName)) {
inputStream = ftpInter.retrieveFileStream(new String(fileName.getBytes("gb2312"), "ISO-8859-1"));
}
}
if (inputStream != null) {
byte[] data = null;
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
data = new byte[inputStream.available()];
int len = 0;
while ((len = inputStream.read(data)) != -1) {
outStream.write(data, 0, len);
}
data = outStream.toByteArray();
Encoder encoder = Base64.getEncoder();
re = encoder.encodeToString(data);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ftpInter.isConnected()) {
try {
ftpInter.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != inputStream) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return re;
}
public static boolean disconnect() {
connFlag = false;
try {
if (ftpInter != null) {
int reply = ftpInter.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpInter.disconnect();
System.err.println("FTP server refused connection.");
System.exit(1);
}
ftpInter.logout();
log.info("断开" + interHost);
}
} catch (IOException e) {
log.error(e.getMessage());
return false;
} finally {
try {
ftpInter.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
return true;
}
}
ImgUtils
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class ImgUtils {
/* 图片转化成base64字符串
*
* @param imgPath
* @return
*/
@SuppressWarnings("restriction")
public static String GetImageStr(String imgPath) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
String imgFile = imgPath;// 待处理的图片
InputStream in = null;
byte[] data = null;
String encode = null; // 返回Base64编码过的字节数组字符串
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
try {
// 读取图片字节数组
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
encode = encoder.encode(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return encode;
}
/**
* base64字符串转化成图片
*
* @param imgData 图片编码
* @param imgFilePath 存放到本地路径
* @return
* @throws IOException
*/
@SuppressWarnings({ "finally", "restriction" })
public static boolean GenerateImage(String imgData, String imgFilePath) throws IOException {
// 对字节数组字符串进行Base64解码并生成图片
if (imgData == null) // 图像数据为空
return false;
BASE64Decoder decoder = new BASE64Decoder();
OutputStream out = null;
try {
out = new FileOutputStream(imgFilePath);
// Base64解码
byte[] b = decoder.decodeBuffer(imgData);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
out.write(b);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
out.flush();
out.close();
return true;
}
}
}
Controller
@RestController
@RequestMapping("/test")
public class TestController {
@PostMapping("/ftptest")
public void qycx(String[] args) throws IOException {
// 连接ftp
FtpHandler.connect();
//ftp图片所在的文件夹路径
String ftpUrl = "/Test/FtpTest";
//图片名称
String sfzh = "测试图片.jpg";
//下载图片
String re = FtpHandler.download(ftpUrl, sfzh);//此时拿到的是图片的base64数据
System.out.println(re);
//本地下载图片路径
String imgpath = "D:\\Daisy\\FtpTest\\" + sfzh;
//将base64字符串转化成图片
ImgUtils.GenerateImage(re, imgpath);
}
}