Java中Telegram bot接收照片转字节数组存入数据库问题咨询
解决方案
现有代码已经完成了从Telegram接口拉取照片文件的逻辑,只需补充输入流转字节数组的逻辑,即可实现存入数据库的需求,具体调整如下:
注意事项
- Telegram返回的
PhotoSize列表是按分辨率从小到大排序的,get(0)拿到的是最低清的缩略图,若需要存储原图建议改为取列表最后一个元素:update.getMessage().getPhoto().get(photo.size() - 1) - 流操作需做好异常处理和资源释放,避免内存泄漏
- 数据库中存储照片的字段需设置为
BLOB类型,若单张照片大小超过64KB建议使用MEDIUMBLOB(最大16MB)或LONGBLOB(最大4GB)
调整后代码
import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.api.objects.PhotoSize; import org.telegram.telegrambots.meta.api.methods.GetFile; import java.io.*; import java.sql.Connection; import java.sql.PreparedStatement; import java.util.List; public void onUpdateReceived(Update update) { this.responseText = "Kerakli bo'limni tanlang:"; if (update.hasMessage() && update.getMessage().hasPhoto()) { this.chatId = update.getMessage().getChatId(); List<PhotoSize> photoList = update.getMessage().getPhoto(); // 取最高分辨率的照片 String fileId = photoList.get(photoList.size() - 1).getFileId(); GetFile getFile = new GetFile(); getFile.setFileId(fileId); File file = getFileRequest(getFile); byte[] photoBytes = null; // 自动关流的try-with-resources语法 try (InputStream inputStream = new FileInputStream(file); ByteArrayOutputStream baos = new ByteArrayOutputStream()) { byte[] buffer = new byte[4096]; int len; while ((len = inputStream.read(buffer)) != -1) { baos.write(buffer, 0, len); } photoBytes = baos.toByteArray(); // JDK 9及以上可以直接用一行代码代替上面的读写逻辑: // photoBytes = inputStream.readAllBytes(); } catch (IOException e) { e.printStackTrace(); // 自定义异常处理逻辑,比如给用户发上传失败的提示 } // 字节数组存入数据库逻辑示例 if (photoBytes != null) { String sql = "INSERT INTO tg_photos (chat_id, photo_content) VALUES (?, ?)"; // 这里用你自己项目的数据库连接获取逻辑替换getYourDatabaseConnection() try (Connection conn = getYourDatabaseConnection(); PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setLong(1, this.chatId); pstmt.setBytes(2, photoBytes); pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } } } }
内容的提问来源于stack exchange,提问作者Shahzodbek Pulatbekov
相关产品推荐
相关产品推荐

