针对文件流转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;
import java.io.IOException;
import java.io.InputStream;
class FileConvertBase64 {
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;
}
public static String getBase64FromInputStream(InputStream in) {
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);
}
public static void download(String urlString, String filename, String savePath, Integer imgId) throws Exception {
URL url = new URL(urlString);
URLConnection con = url.openConnection();
con.setConnectTimeout(5 * 1000);
InputStream is = con.getInputStream();
String base64FromInputStream = getBase64FromInputStream(is);
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();
}
}