最近要實現一個發佈博客功能,涉及到博文中圖片的保存與訪問了,在博文中圖片對應:
。由用戶上傳圖片,咱們將其保存在 mongodb 數據庫中,返回圖片的 url 便可顯示圖片了。
在這裏把基本實現步驟整理了一下記錄下來
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>
spring: data: mongodb: uri: mongodb://192.168.56.101:27017/sysblog
import org.bson.types.Binary; @Document public class UploadFile { @Id private String id; private String name; // 文件名 private Date createdTime; // 上傳時間 private Binary content; // 文件內容 private String contentType; // 文件類型 private long size; // 文件大小 // getter/setter }
new Binary(byte[] byte)
此處僅演示功能,便不分層等操做。前端
上傳圖片後,保存至 mongodb 數據庫,並返回圖片的訪問 url
@Autowired private MongoTemplate mongoTemplate; @PostMapping("/file/uploadImage") @ResponseBody public String uploadImage(@RequestParam(value = "image") MultipartFile file){ if(file.isEmpty()) return JSONResult.build(200, "請選擇一張圖片", null); // 返回的 JSON 對象,這種類可本身封裝 JSONResult jsonResult = null; String fileName = file.getOriginalFilename(); try { UploadFile uploadFile = new UploadFile(); uploadFile.setName(fileName); uploadFile.setCreatedTime(new Date()); uploadFile.setContent(new Binary(file.getBytes())); uploadFile.setContentType(file.getContentType()); uploadFile.setSize(file.getSize()); UploadFile savedFile = mongoTemplate.save(uploadFile); String url = "http://localhost:8080/file/image/"+ savedFile.getId(); jsonResult = JSONResult.build(200, "圖片上傳成功", url); } catch (IOException e) { e.printStackTrace(); jsonResult = JSONResult.build(500, "圖片上傳失敗", null); } return jsonResult; }
你也能夠建立一個 repository 層接口繼承 MongoRepository,相似於 JPA 的操做。java
JSONResult(狀態碼, 信息, 數據);
spring
根據圖片 id 獲取圖片
import org.springframework.http.MediaType; @GetMapping(value = "/file/image/{id}", produces = {MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE}) @ResponseBody public byte[] image(@PathVariable String id){ byte[] data = null; UploadFile file = mongoTemplate.findImageById(id, UploadFile.class); if(file != null){ data = file.getContent().getData(); } return data; }
在 markdown 編輯器中插入圖片,簡直完美:mongodb