根据URL下载网络文件
代码如下(示例):
public static byte[] readFile(String url)
{
InputStream in = null;
try
{
if (url.startsWith("http"))
{
// 网络地址
URL urlObj = new URL(url);
URLConnection urlConnection = urlObj.openConnection();
urlConnection.setConnectTimeout(30 * 1000);
urlConnection.setReadTimeout(60 * 1000);
urlConnection.setDoInput(true);
in = urlConnection.getInputStream();
}
else
{
// 本机地址
String localPath = RuoYiConfig.getProfile();
String downloadPath = localPath + StringUtils.substringAfter(url, Constants.RESOURCE_PREFIX);
in = new FileInputStream(downloadPath);
}
return IOUtils.toByteArray(in);
}
catch (Exception e)
{
log.error("获取文件路径异常 {}", e);
return null;
}
finally
{
IOUtils.closeQuietly(in);
}
}
将下载数据转成文件
代码如下(示例):
public static void createJsFile(File file, byte[] data){
try(
FileOutputStream fos = new FileOutputStream(file);
){
fos.write(data);
}catch (FileNotFoundException fnoe){
fnoe.printStackTrace();
}catch (IOException ioe){
ioe.printStackTrace();
}
}
本地文件(图片、excel等)转换成Base64字符串
代码如下(示例):
public static String convertFileToBase64(String imgPath) {
byte[] data = null;
// 读取图片字节数组
try {
InputStream in = new FileInputStream(imgPath);
System.out.println("文件大小(字节)="+in.available());
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
log.error("图片转换Base64字符串异常 {}", e);
}
// 对字节数组进行Base64编码,得到Base64编码的字符串
BASE64Encoder encoder = new BASE64Encoder();
String base64Str = encoder.encode(data);
return base64Str;
}
将base64字符串,生成文件
代码如下(示例):
public static File convertBase64ToFile(String fileBase64String, String filePath, String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File(filePath);
if (!dir.exists() && dir.isDirectory()) {//判断文件目录是否存在
dir.mkdirs();
}
BASE64Decoder decoder = new BASE64Decoder();
byte[] bfile = decoder.decodeBuffer(fileBase64String);
file = new File(filePath + File.separator + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bfile);
return file;
} catch (Exception e) {
log.error("Base64字符串转换图片异常 {}", e);
return null;
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
代码测试
public static void main(String[] args) {
String url = "http://gas.chuqv.top/f7b3e36ed0fbfecf2c77db2d63ce99b6.jpg";
byte[] date = ImageUtils.readFile(url);
File file1 = new File("C:\\Users\\54626\\Desktop\\", "1.jpg");
createJsFile(file1, date);
String result = convertFileToBase64("C:\\Users\\54626\\Desktop\\1.jpg");
convertBase64ToFile(result,"C:\\Users\\54626\\Desktop\\","11.jpg");
}