一.业务
在业务中我们被要求将文件或图片等转成 byte[] 或 inputstream存到数据库的blob类型的字段中.
二.blob类型介绍
在 mysql 中,blob 数据类型用于存储二进制数据。mysql 提供了四种不同的 blob 类型:
tinyblob: 最大存储长度为 255 个字节。blob: 最大存储长度为 65,535 个字节。mediumblob: 最大存储长度为 16,777,215 个字节。longblob: 最大存储长度为 4,294,967,295 个字节。
三. blob 对应的 java 类型
在 java 中读取 mysql blob 类型时,通常使用 java.sql.blob 类型。java.sql.blob 是一个接口,它提供了一些方法来操作 blob 数据。
根据 mysql blob 类型的不同,我们可以使用不同的 java 类型来存储 blob 数据。
- tinyblob 对应
byte[]或inputstream。 - blob 对应
byte[]或inputstream。 - mediumblob 对应
byte[]或inputstream。 - longblob 对应
byte[]或inputstream。
我们可以根据需要选择合适的 java 类型。推荐用inputstream,这样代码不用转换来转换去,比较简单
四.上存取java代码
1.建表

2.建实体类
@data
public class ttt {
private string id;
private string name;
private string createtime;
private byte[] miaoshubyte;
private inputstream miaoshuinputstream;
}3.用个自己写的工具类
public class fileutil {
/**
* file转byte
*/
public static byte[] file2byte(file file) throws ioexception {
fileinputstream fis = null;
bytearrayoutputstream bos = null;
try {
fis = new fileinputstream(file);
bos = new bytearrayoutputstream();
ioutils.copy(fis, bos);
byte[] bytes = bos.tobytearray();
return bytes;
}finally {
if (fis != null) {
fis.close();
}
if (bos != null) {
bos.close();
}
}
}
/**
* byte 转file
*/
public static file byte2file(byte[] buf,string filename) throws ioexception {
fileoutputstream fos = null;
try {
fos = new fileoutputstream(filename);
fos.write(buf);
file file = new file(filename);
return file;
} finally {
if (fos != null) {
fos.close();
}
}
}
} 4.访问接口
@restcontroller
@requestmapping("order/")
@slf4j
public class sendhttpwcontroller {
@autowired
private utimeemapper utimeemapper;
@getmapping("/aa")
public string querybyid( integer id) throws ioexception {
ttt ttt = new ttt();
ttt.setid("30");
ttt.setname("张三");
file file = new file("f:\\desktop\\aa.docx");
byte[] bytes = fileutil.file2byte(file);
ttt.setmiaoshubyte(bytes);
fileinputstream fileinputstream = new fileinputstream(file);
ttt.setmiaoshuinputstream(fileinputstream);
utimeemapper.insert01(ttt);
return "嘿嘿额黑8082";
}
@getmapping("/bb")
public string bb( integer id) throws ioexception {
ttt ttt = utimeemapper.select01("30");
byte[] bytes = ttt.getmiaoshubyte();
fileutil.byte2file(bytes,"f:\\desktop\\cc.docx");
inputstream inputstream = ttt.getmiaoshuinputstream();
fileoutputstream outputstream = new fileoutputstream("f:\\desktop\\dd.docx");
ioutils.copy(inputstream, outputstream);//记得添加关流代码(本代码省略了)
return "嘿嘿额黑8082";
}5.输出成果

总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论