How to use GridFSBucket in Java to store files such as images, audio, and videos to MongoDB
To use GridFSBucket in Java to store files in MongoDB, you need to first import MongoDB's Java driver (such as mongodb driver) and GridFSBucket's class (org. mongodb: gridfs).
The following is a complete sample code for storing image files to MongoDB using GridFSBucket:
Firstly, ensure that you have added the following dependencies to the Maven project:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.4.1</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-core</artifactId>
<version>4.4.1</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>bson</artifactId>
<version>4.4.1</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>4.4.1</version>
</dependency>
2. Write Java code:
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import com.mongodb.client.gridfs.GridFSFindIterable;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.mongodb.client.gridfs.model.GridFSUploadOptions;
import org.bson.Document;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class MongoGridFSExample {
public static void main(String[] args) {
//MongoDB connection parameters
String host = "localhost";
int port = 27017;
String databaseName = "test";
String username = "username";
String password = "password";
//Create MongoDB client
MongoCredential credential = MongoCredential.createCredential(username, databaseName, password.toCharArray());
ServerAddress serverAddress = new ServerAddress(host, port);
MongoClientSettings settings = MongoClientSettings.builder()
.credential(credential)
.applyToSslSettings(builder -> builder.enabled(false))
.applyToClusterSettings(builder -> builder.hosts(Arrays.asList(serverAddress)))
.build();
MongoClient mongoClient = MongoClients.create(settings);
//Get GridFSBucket
GridFSBucket gridFSBucket = GridFSBuckets.create(mongoClient.getDatabase(databaseName));
//Upload files
String filePath = "path_to_file/image.jpg";
String fileName = "image.jpg";
try (InputStream streamToUploadFrom = new FileInputStream(filePath)) {
GridFSUploadOptions options = new GridFSUploadOptions()
.chunkSizeBytes(1024)
.metadata(new Document("type", "image"));
String fileId = gridFSBucket.uploadFromStream(fileName, streamToUploadFrom, options);
System.out.println("File uploaded with id: " + fileId);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Query files based on file name
GridFSFindIterable files = gridFSBucket.find(new Document("filename", fileName));
GridFSFile file = files.first();
if (file != null) {
System.out.println("File name: " + file.getFilename());
System.out.println("File size: " + file.getLength());
System.out.println("File type: " + file.getMetadata().getString("type"));
//You can obtain the file ID through file. getObject Id () and download the file through gridFSBucket. openDownloadStream (file. getObject Id ())
} else {
System.out.println("File not found");
}
//Close MongoDB client
mongoClient.close();
}
}
This sample code demonstrates how to use GridFSBucket to upload image files to MongoDB, query files based on file names, and obtain some basic information. Please make modifications and extensions according to your specific needs.
It should be noted that the above code assumes that you have already run the MongoDB server locally and set authentication information such as username and password. Please make corresponding changes based on your actual situation.
Reference documents:
-MongoDB official Java driver documentation: https://mongodb.github.io/mongo-java-driver/
-GridFSBucket class documentation and examples: https://mongodb.github.io/mongo-java-driver/4.4/driver/tutorials/gridfs/
-MongoDB official document: https://docs.mongodb.com/