Base64与File之间的相互转化方式
更新时间:2022年02月09日 10:12:47 作者:魔道不误砍柴功
这篇文章主要介绍了Base64与File之间的相互转化方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
Base64与File的相互转化
问题
最近遇到一个上传文件的问题,前端使用了另一种传值,就是Base64字符串传给后台 ,一开始没有对其进行解码操作,存入数据库时就超长了,今天这里提供一种base64和file之间相互转化的工具类,以便日后参考
/**
*
* @param path
* @return String
* @description 将文件转base64字符串
* @date 2018年3月20日
* @author changyl
* File转成编码成BASE64
*/
public static String fileToBase64(String path) {
String base64 = null;
InputStream in = null;
try {
File file = new File(path);
in = new FileInputStream(file);
byte[] bytes=new byte[(int)file.length()];
in.read(bytes);
base64 = Base64.getEncoder().encodeToString(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return base64;
}//BASE64解码成File文件
public static void base64ToFile(String destPath,String base64, String fileName) {
File file = null;
//创建文件目录
String filePath=destPath;
File dir=new File(filePath);
if (!dir.exists() && !dir.isDirectory()) {
dir.mkdirs();
}
BufferedOutputStream bos = null;
java.io.FileOutputStream fos = null;
try {
byte[] bytes = Base64.getDecoder().decode(base64);
file=new File(filePath+"/"+fileName);
fos = new java.io.FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}需要注意
标红的base64在这里需要去掉
baseStr = baseStr.replace("data:image/jpeg;base64,", "");//base64解密部分乱码问题(“+” 号,在urlecode编码中会被解码成空格)将Base64转为文件并保存
public static void base64ToFile(String base64, String fileName, String savePath) {
File file = null;
//创建文件目录
String filePath = savePath;
File dir = new File(filePath);
if (!dir.exists() && !dir.isDirectory()) {
dir.mkdirs();
}
BufferedOutputStream bos = null;
java.io.FileOutputStream fos = null;
try {
byte[] bytes = Base64.getDecoder().decode(base64);
file=new File(filePath + fileName);
fos = new java.io.FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Springboot打包代码,反编译后代码混淆方式(防止还原代码)
文章主要介绍了如何对Spring Boot项目进行jar包混淆,以防止反编译还原原始代码,通过在项目中添加proguard.cfg文件并配置Maven插件,可以实现代码混淆,从而增加反编译的难度2024-11-11
java并发编程包JUC线程同步CyclicBarrier语法示例
这篇文章主要为大家介绍了java并发编程工具包JUC线程同步CyclicBarrier语法使用示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2022-03-03
java.io.EOFException: Unexpected end of
本文主要介绍了java.io.EOFException: Unexpected end of ZLIB input stream异常解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2023-05-05


最新评论