一.业务
在业务中我们被要求将文件或图片等转成 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.建实体类
1 2 3 4 5 6 7 8 | @Data public class TTT { private String id; private String name; private String createTime; private byte [] miaoshuByte; private InputStream miaoshuInputstream; } |
3.用个自己写的工具类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | 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.访问接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | @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.输出成果
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持IT俱乐部。