In this tutorial, we show you how to save an image file into MongoDB, via GridFS API. The GridFS APIs are able to serve other binary files as well, like video and music files.

1. Save image

Code snippets to save an image file into MongoDB, under “photo” namespace, and assign a new “filename” for the saved image.

	String newFileName = "mkyong-java-image";
File imageFile = new File("c:\\JavaWebHosting.png");
GridFS gfsPhoto = new GridFS(db, "photo");
GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
gfsFile.setFilename(newFileName);
gfsFile.save();

2. Get image

Code snippets to get the saved image by its “filename”.

	String newFileName = "mkyong-java-image";
GridFS gfsPhoto = new GridFS(db, "photo");
GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);
System.out.println(imageForOutput);

Output, the image is saved as following JSON format.

{
"_id" :
{
"$oid" : "4dc9511a14a7d017fee35746"
} ,
"chunkSize" : 262144 ,
"length" : 22672 ,
"md5" : "1462a6cfa27669af1d8d21c2d7dd1f8b" ,
"filename" : "mkyong-java-image" ,
"contentType" : null ,
"uploadDate" :
{
"$date" : "2011-05-10T14:52:10Z"
} ,
"aliases" : null
}

3. Print all saved images

Code snippets to get all the saved files from MongoDB and iterate it with DBCursor.

	GridFS gfsPhoto = new GridFS(db, "photo");
DBCursor cursor = gfsPhoto.getFileList();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}

4. Save into another image

Code snippets to get an image file from MongoDB and output it to another image file.

	String newFileName = "mkyong-java-image";
GridFS gfsPhoto = new GridFS(db, "photo");
GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);
imageForOutput.writeTo("c:\\JavaWebHostingNew.png"); //output to new file

5. Delete image

Code snippets to delete an image file.

	String newFileName = "mkyong-java-image";
GridFS gfsPhoto = new GridFS(db, "photo");
gfsPhoto.remove(gfsPhoto.findOne(newFileName));

Full Example

Full example to work with image, via Java MongoDB GridFS API. See comments for explanation.

package com.mkyong.core;

import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile; /**
* Java MongoDB : Save image example
*
*/ public class SaveImageApp {
public static void main(String[] args) { try { Mongo mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("imagedb");
DBCollection collection = db.getCollection("dummyColl"); String newFileName = "mkyong-java-image"; File imageFile = new File("c:\\JavaWebHosting.png"); // create a "photo" namespace
GridFS gfsPhoto = new GridFS(db, "photo"); // get image file from local drive
GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile); // set a new filename for identify purpose
gfsFile.setFilename(newFileName); // save the image file into mongoDB
gfsFile.save(); // print the result
DBCursor cursor = gfsPhoto.getFileList();
while (cursor.hasNext()) {
System.out.println(cursor.next());
} // get image file by it's filename
GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName); // save it into a new image file
imageForOutput.writeTo("c:\\JavaWebHostingNew.png"); // remove the image file from mongoDB
gfsPhoto.remove(gfsPhoto.findOne(newFileName)); System.out.println("Done"); } catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} }
}

At the end of the program, a new image file is created in “c:\\JavaWebHostingNew.png“.

Java MongoDB : Save image example的更多相关文章

  1. Java + MongoDB Hello World Example--转载

    原文地址:http://www.mkyong.com/mongodb/java-mongodb-hello-world-example/ A simple Java + MongoDB hello w ...

  2. 【MongoDB数据库】Java MongoDB CRUD Example

    上一页告诉我们MongoDB 命令入门初探,本篇blog将基于上一篇blog所建立的数据库和表完毕一个简单的Java MongoDB CRUD Example.利用Java连接MongoDB数据库,并 ...

  3. java MongoDB查询(二)复杂查询

    前言 在上篇<java MongoDB查询(一)简单查询>中我们简单了解了下查询,但是仅仅有那些查询是不够用的,还需要复杂的查询,这篇就这点进行叙述. 1.数据结构 集合:firstCol ...

  4. MongoDB save()方法和insert()方法的区别

    MongoDB save()方法和insert()方法的区别 首先看官方文档怎么说的 Updates an existing document or inserts a new document, d ...

  5. Java mongodb api疑问之MongoCollection与DBCollection

    在学习Java mongodb api时发现,可以调用不同的java mongodb api来连接数据库并进行相关操作. 方式一: 该方式使用mongoClient.getDB("xxx&q ...

  6. Java MongoDB插入

    前言 插入是向MongoDB中添加数据的基本方法.对目标集使用insert方法来插入一条文档.这个方法会给文档增加一个”_id”属性(如果原来没有的话),然后保存到数据库中. 1.连接数据库,拿到集合 ...

  7. java mongodb 增删改查 工具类

    package com.jttx.demo;   import com.mongodb.*; import com.mongodb.util.JSON;   import java.net.Unkno ...

  8. java mongoDB 二级数组嵌套查询

    场景: 会员集合下有多个会员文档,会员文档下有多个订单文档,订单买了多个商品文档 member->orders>orderItems 要求: 通过会员id和商品id验证会员是否购买过该商品 ...

  9. Java MongoDB Driver 3.x - Quick Start

    Maven Dependency: <dependency> <groupId>org.mongodb</groupId> <artifactId>mo ...

随机推荐

  1. API Authentication Error: {"error":"invalid_client","message":"Client authentication failed"}

    解决方法:https://github.com/laravel/passport/issues/221 In your oauth_clients table, do the values you h ...

  2. 疯狂Android讲义

    1 Android应用和开发环境2 Android应用的界面编程3 Android的事件处理4 Activity Fragment5 Intent IntentFilter6 Android应用的资源 ...

  3. classpath 及读取 properties 文件

    java代码中获取项目的静态文件,如获取 properties 文件内容是必不可少的. Spring 下只需要通过 @Value 获取配置文件值 <!-- 资源文件--> <util ...

  4. JavaScript - Scope of variables

    It's important to note, especially if you have come to JavaScript from another language, that variab ...

  5. Docker中执行Shell出现乱码

    问题描述 最近遇到一个问题: 执行命令 docker exec f4af9b sh -c 'bash /tmp/build.sh' 命令在docker中执行shell,会出现中文乱码的问题.但是在do ...

  6. 列表函数&方法

    列表(list)的基本操作,方法及属性.

  7. 30、hashCode方法

    HashCode方法的作用 在HashSet中的元素是不能重复的,jvm可以通过equals方法来判断两个对象是否相同,假设自定义一个Person类里面有10个成员变量,每调用一次equals方法需要 ...

  8. js 各类判断用户输入字符的格式函数

    1.JS 判断IP格式是否正确: function checkIP(ip) { var regular = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/;//正则表达式 if (reg ...

  9. 【总结】2017年当下最值得你关注的前端开发框架,不知道你就OUT了!

    近几年随着 jQuery.Ext 以及 CSS3 的发展,以 Bootstrap 为代表的前端开发框架如雨后春笋般挤入视野,可谓应接不暇. 在这篇分享中,我将总结2017年当下最值得你关注的前端开发框 ...

  10. std::max 错误

    Today I typed the following: int t = (std::max)(timeout, lagtime); Why did I put parentheses around ...