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. 【Asp.net入门3-05】处理JSON数据

  2. Head内常用标签

    一.标签分类 1.1 自闭和标签 自闭和标签只有开头没有结尾,自动闭合: <meta> 标签 <link> 标签 1.2主动闭合标签 有开头也有结尾,是主动闭合的,称为主动闭合 ...

  3. Linux /etc/issue 和 /etc/issue.net的作用和区别

    1./etc/motd /etc/motd即messageoftoday(布告栏信息),每次用户登录时,/etc/motd文件的内容会显示在用户的终端.系统管理员可以在文件中编辑系统活动消息,例如:管 ...

  4. COGS 513 八

    513. 八 http://www.cogs.pro/cogs/problem/problem.php?pid=513 ★☆   输入文件:eight.in   输出文件:eight.out   简单 ...

  5. HDU 4135 容斥

    问a,b区间内与n互质个数,a,b<=1e15,n<=1e9 n才1e9考虑分解对因子的组合进行容斥,因为19个最小的不同素数乘积即已大于LL了,枚举状态复杂度不会很高.然后差分就好了. ...

  6. github 新创建repositories

    1. 在github上新建repo 2. 找到改repo的地址,用命令git clone https://....,  拉取到本地 3. 打开一个单独的窗口,打开此文件夹 4. 创建自己的python ...

  7. Linux声音系统

    TAG: linux, alsa, oss, pulseaudio, esd, aRts DATE: 2013-08-13 Linux声音系统有些混乱,它有三套音频驱动: OSS (Open Soun ...

  8. django错误笔记——URL

    django提交表单提示"RuntimeError: You called this URL via POST, but the URL doesn’t end in a slash and ...

  9. Unix/Linux系统时间函数API

    首先说明关于几个时间的概念: 世界时:起初,国际上的标准时间是格林尼治标准时间,以太阳横穿本初子午线的时刻为标准时间正午12点.它根据天文环境来定义,就像古代人们根据日晷来计时一样,如下图: 原子时: ...

  10. Spring4笔记9--Spring的事务管理(AOP应用的例子)

    Spring的事务管理: 事务原本是数据库中的概念,在 Dao 层.但一般情况下,需要将事务提升到业务层,即 Service 层.这样做是为了能够使用事务的特性来管理具体的业务.   在 Spring ...