一.業務
在業務中我們被要求將文件或圖片等轉成?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 {@Autowiredprivate 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.輸出成果