簡體   English   中英

如何使用Java將圖像和一些數據存儲在MongoDB中

[英]How to store Image with some data in MongoDB using Java

例如:

我想存儲員工詳細信息,例如

private Long id;
private String Name;
private String country;

現在,我還想將一個圖像以及以上數據存儲在MongoDB中。

在我的控制器中,我在下面的代碼中編寫了一個代碼段

Employee employee2 = new Employee(); 
employee2.setEmpId(1002);
employee2.setEmpName("Dinesh Rajput");
employee2.setCountry("India");

mongoOperations.save(employee2);

員工數據在數據庫中創建。 現在如何存儲圖像。

您可以添加如下代碼

DBObject metaData = new BasicDBObject();
metaData.put("mobileNo", mobileNo);
metaData.put("FileName", fileName);
metaData.put("createDate", new Date());

它將像這樣保存在數據庫中

假設您使用的是Spring Boot,Spring Data Mongo,則應考慮將Spring Content for Mongo用於內容存儲,如下所示:

將以下依賴項添加到pom.xml

<dependency>
    <groupId>com.github.paulcwarren</groupId>
    <artifactId>spring-content-mongo-boot-starter</artifactId>
    <version>0.0.10</version>
</dependency>
<dependency>
    <groupId>com.github.paulcwarren</groupId>
    <artifactId>spring-content-rest-boot-starter</artifactId>
    <version>0.0.10</version>
</dependency>

確保您的應用程序上下文中存在GridFsTemplate bean。 類似於以下內容:

@Configuration
public class MongoConfig

   @Bean
   public GridFsTemplate gridFsTemplate() throws Exception {
      return new GridFsTemplate(mongoDbFactory(), mappingMongoConverter());
   }
   ...

要允許內容與您的Employee實體相關聯,請為其提供以下屬性:

@ContentId
private String contentId;

@ContentLength 
private long contentLength = 0L;

@MimeType
private String mimeType = "text/plain";

添加商店界面:

@StoreRestResource(path="employeeImages")
public interface EmployeeImageStore extends ContentStore<Employee, String> {
}

這就是您所需要的。 當您的應用程序啟動時,Spring Content將看到Mongo / REST模塊上的依賴關系,它將為GridFs注入EmployeeImageStore存儲的實現,以及支持完全CRUD功能並將這些操作映射到底層存儲的控制器的實現。接口。 REST端點將在/employeeImages下可用。

curl -X PUT /employeeImages/{employeeId}將創建或更新員工的圖像

curl -X GET /employeeImages/{employeeId}將獲取員工的圖像

curl -X DELETE /employeeImages/{employeeId}將刪除員工的圖像

有一對夫婦快速入門指南的在這里 他們將Spring Content用於文件系統,但是模塊是可互換的。 Mongo參考指南在這里 而且還有視頻教程在這里

高溫超導

您有2個選項可以實現此目的。

  1. 將圖像保存到本地系統並在java對象中添加屬性,例如imagePath
  2. 使用GridFS將其存儲為二進制數據

有關如何使用GridF的教程

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM