一.业务
在业务中我们被要求将文件或图片等转成 或 存到数据库的 类型的字段中.
二.Blob类型介绍
在 MySQL 中,Blob 数据类型用于存储二进制数据。MySQL 提供了四种不同的 Blob 类型:
- : 最大存储长度为 255 个字节。
- : 最大存储长度为 65,535 个字节。
- : 最大存储长度为 16,777,215 个字节。
- : 最大存储长度为 4,294,967,295 个字节。
三. Blob 对应的 Java 类型
在 Java 中读取 MySQL Blob 类型时,通常使用 类型。 是一个接口,它提供了一些方法来操作 Blob 数据。
根据 MySQL Blob 类型的不同,我们可以使用不同的 Java 类型来存储 Blob 数据。
- TINYBLOB 对应或。
- BLOB 对应或。
- MEDIUMBLOB 对应或。
- LONGBLOB 对应或。
我们可以根据需要选择合适的 Java 类型。推荐用,这样代码不用转换来转换去,比较简单
四.上存取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.输出成果
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持晓枫资讯。 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |