沒有文件服務(wù)器,頭像存哪里合適
視頻在bilibili:沒有文件服務(wù)器,頭像存哪里合適
1. 背景
之前有同學(xué)私信我說,他的項(xiàng)目只是想存?zhèn)€頭像,沒有別的文件存儲(chǔ)需求,不想去用什么Fastdfs之類的方案搭建文件服務(wù)器,有沒有更簡(jiǎn)單且無需后期維護(hù)的方案,我喝了一口過期的開水,想了下,還真有,現(xiàn)在就給大家介紹一下。
這個(gè)方案就是把頭像存在表里,但是要切記,不要存大圖,否則會(huì)嚴(yán)重影響數(shù)據(jù)庫性能,怎么確保這一點(diǎn)呢,其實(shí)只要對(duì)上傳的圖片轉(zhuǎn)成縮略圖就可以保證存進(jìn)去的是小圖,這樣的話這個(gè)方案就比較完美了。
2. 關(guān)鍵步驟梳理
2.1 數(shù)據(jù)庫設(shè)計(jì)
字段的類型應(yīng)該是blob, blob是一種二進(jìn)制存儲(chǔ)類型,用來存儲(chǔ)圖片完全是沒問題的
2.2 后端接口
-
Controller
@Operation(summary = "修改頭像") @PostMapping("/avatar") public Result<?> updateAvatar(MultipartFile file, @RequestParam("userId") Integer userId) throws IOException, SQLException { // 讀取上傳的原始圖片 BufferedImage originalImage = ImageIO.read(file.getInputStream()); // 創(chuàng)建縮略圖 int thumbnailSize = 200; // 計(jì)算縮略圖的寬度和高度,保持原寬高比例 int newWidth, newHeight; if (originalImage.getWidth() > originalImage.getHeight()) { newWidth = thumbnailSize; newHeight = thumbnailSize * originalImage.getHeight() / originalImage.getWidth(); } else { newWidth = thumbnailSize * originalImage.getWidth() / originalImage.getHeight(); newHeight = thumbnailSize; } // 創(chuàng)建縮略圖 BufferedImage thumbnail = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = thumbnail.createGraphics(); graphics2D.drawImage(originalImage, 0, 0, newWidth, newHeight, null); graphics2D.dispose(); // 裁剪成以圖片中心為中心的正方形,因?yàn)榍岸耸且哉叫物@示 int x = 0; int y = 0; int cropSize = Math.min(newWidth, newHeight); if (newWidth > newHeight) { x = (newWidth - cropSize) / 2; } else { y = (newHeight - cropSize) / 2; } thumbnail = thumbnail.getSubimage(x, y, cropSize, cropSize); ByteArrayOutputStream bs = new ByteArrayOutputStream(); ImageIO.write(thumbnail, "jpg", bs); byte[] thumbnailBytes = bs.toByteArray(); userService.updateAvatar(userId,thumbnailBytes); return Result.success(); } @Operation(summary = "查詢頭像") @GetMapping("/avatar") public Result<?> getAvatar(@RequestParam("userId") Integer userId){ byte[] arvatarData = userService.getAvatar(userId); return Result.success(arvatarData); }
-
Service
@Override public void updateAvatar(Integer userId, byte[] avatar) throws SQLException { log.debug("avatar: " + avatar.length); SerialBlob avatarBlob = new SerialBlob(avatar); userMapper.updateAvatar(userId,avatarBlob); } @Override public byte[] getAvatar(Integer userId) { User user = userMapper.selectById(userId); return user.getAvatarData(); }
-
Mapper文章來源:http://www.zghlxwxcb.cn/news/detail-861393.html
@Update("update wj_user set avatar_data=#{avatarBlob} where id = #{userId}") void updateAvatar(Integer userId, Blob avatarBlob);
3 前端關(guān)鍵代碼
文章來源地址http://www.zghlxwxcb.cn/news/detail-861393.html
到了這里,關(guān)于沒有文件服務(wù)器,頭像存哪里合適的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!