首页 > 解决方案 > 将文件 base64 保存在 blob 列中

问题描述

我有一个像这样的可变字符串 base 64:

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQA.......

我需要将其保存在列类型 blob 中,我需要解码我认为的字符串以及保存到 blob 列之前的更多内容

标签: javaspring-batchblob

解决方案


根据RFC 2397,在您的情况下,BASE64 字符串的 URL 部分data:image/jpeg;base64

假设您使用标准 Base64 解码器,那么您需要拆分字符串才能将其解码为图像,如下面的代码所示:

import java.io.ByteArrayInputStream;
import sun.misc.BASE64Decoder;


def sourceData = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQA';

// tokenize the data
def parts = sourceData.tokenize(",");
def imageString = parts[1];

// create a buffered image
BufferedImage image = null;
byte[] imageByte;

BASE64Decoder decoder = new BASE64Decoder();
imageByte = decoder.decodeBuffer(imageString);
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
image = ImageIO.read(bis);
bis.close();

// write the image to a file
File outputfile = new File("response.jpg");
ImageIO.write(image, "jpg", outputfile);

因此,如果您想保存与图像文件格式相关的信息,请在保存到 Database Clob Column 时保留 Full Base64 String,并且在读取时您只能将 DATA PART(在 Base64 URL 之后)解码为实际图像而 base64 URL 可以帮助确定图像的格式。


推荐阅读