java文件转base64
package org.Util;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
/**
* @author Hmoumou
* @DATE 2022/1/3
* @apiNote
*/
import java.io.IOException;
import java.io.InputStream;
/**
* @Description 文件转base64
*/
class FileConvertBase64 {
/**
* 文件转base64
*
* @param filePath
* @return
*/
public static String encryptToBase64(String filePath) {
if (filePath == null) {
return null;
}
try {
byte[] b = Files.readAllBytes(Paths.get(filePath));
return Base64.getEncoder().encodeToString(b);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 将文件输入流转为base64
*/
public static String getBase64FromInputStream(InputStream in) {
// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
byte[] data = null;
// 读取图片字节数组
try {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = in.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
data = swapStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return Base64.getEncoder().encodeToString(data);
}
/**
* 通过图片src下载图片
* 并保存到本地路径
* @param urlString
* @param filename
* @param savePath
* @throws Exception
*/
public static void download(String urlString, String filename, String savePath, Integer imgId) throws Exception {
// 构造URL
URL url = new URL(urlString);
// 打开连接
URLConnection con = url.openConnection();
//设置请求超时为5s
con.setConnectTimeout(5 * 1000);
// 输入流
InputStream is = con.getInputStream();
String base64FromInputStream = getBase64FromInputStream(is);
// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
// 输出的文件流
File sf = new File(savePath);
if (!sf.exists()) {
sf.mkdirs();
}
// 获取图片的扩展名
String extensionName = filename.substring(filename.lastIndexOf(".") + 1);
// 新的图片文件名 = 编号 +"."图片扩展名
String newFileName = imgId + "." + extensionName;
OutputStream os = new FileOutputStream(sf.getPath() + "\\" + filename);
// 开始读取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完毕,关闭所有链接
os.close();
is.close();
}
public static void main(String[] args) throws Exception {
for (int i = 1; i < 10; i++) {
String url = "https://smartdl.lenovo.com.cn/frontend/browser/hao.edge/image/af4616c312d.png"+i;
String fileName = "sftp_test (" + i + ").jpg";
String savePath = "C:\\Users\\Desktop\\testDownload";
download(url, fileName, savePath, i);
String dd = encryptToBase64("C:\\Users\\Desktop\\testDownload\\"+fileName);
System.out.println(dd);
System.out.println("---------------------------------------");
}
}
}