当前位置:网站首页>Base64与File之间的相互转化
Base64与File之间的相互转化
2022-07-29 05:27:00 【魔道不误砍柴功】
问题:最近遇到一个上传文件的问题,前端使用了另一种传值,就是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编码中会被解码成空格)
边栏推荐
猜你喜欢

Complex floating point division of vivado IP core floating point

Complex floating point multiplication of vivado IP core floating point

Floating point multiplication and division of vivado IP core floating point

day16-集合上

Hongke | uses jesd204 serial interface to bridge analog and digital worlds at high speed

Design of IIR filter based on FPGA

8、 Network security

day17_集合下

Conversion of fixed-point number to floating-point number of vivado IP core

Huawei switch ce12808 import and export configuration file
随机推荐
How to use SFTP command to access SFTP server on the development board
FIR滤波器设计(2)——Vivado调用IP核设计FIR滤波器
超低成本DDoS攻击来袭,看WAF如何绝地防护
day14_单元测试&日期常用类&字符串常用类
Hog+svm for pedestrian detection
Traffic characteristics of webshell management tools
Hongke automation SoftPLC | modk operation environment and construction steps (1) -- Introduction to operation environment
FIR filter design (2) -- vivado calls IP core to design FIR filter
5、 Wireless communication network
[interview questions] the latest software test interview questions in 2022 (400) [with answers] continue to update
Multiple IO usage
C语言内存-栈与堆使用
用神经网络实现手写数字识别
IPv6表示方法与配置案例
9、 Networking technology
FIR滤波器设计(1)——利用matlab的fdatool工具箱设计FIR滤波器参数
Arrays&Object&System&Math&Random&包装类
Use of for statement in Verilog
6、 Network interconnection and Internet
比较单片机3种时钟电路方案