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. Ntp服务器的搭建

    在搭建Ntp服务器的过程中,试过两种方案,具体如下: 方案一: 到ntp官网获取源码编译,失败   下载源码ntp-4.2.8 -> ./configure -> make 无法通过:   ...

  2. 十、Shell基础

    一.shell概述 1.Shell是什么 shell是一个命令行解释器,他为用户提供了一个向linux内核发送请求以便运行程序的界面系统级程序,用户可以用shell来启动.挂起.停止甚至编写一些程序 ...

  3. Python之——生产环境代码包发布管理fabirc

    程序生产环境的发布是业务上线最后一个环境,要求具备源码打包.发布.切换.回滚.版本管理等功能,本实例实现了一整套流程,其中版本切换与回滚使用了Linux的软链接来实现.具体代码如下:   # -*- ...

  4. 自定义UITableViewCell的方法

    1.纯XIB/storyboard自定义.对应一个Controller的storyboard上拖拽出一个自定义Cell,并加上ReuseIdentifitor 2.纯代码自定义,通过在contentV ...

  5. bootstrap-switch

    首先需要引入bootstrap的css和js文件,再引入bootstrap-switch.css和bootstrap-switch.js文件 <script type="text/ja ...

  6. Linux服务器上使用curl命令发送报文

    报文格式如下: curl -l -H "Content-type: application/json" -X POST -d 'postdata' http://172.20.10 ...

  7. Java并发编程原理与实战三十八:多线程调度器(ScheduledThreadPoolExecutor)

    在前面介绍了java的多线程的基本原理信息:线程池的原理与使用 本文对这个java本身的线程池的调度器做一个简单扩展,如果还没读过上一篇文章,建议读一下,因为这是调度器的核心组件部分. 我们如果要用j ...

  8. 【BZOJ】2655: calc 动态规划+拉格朗日插值

    [题意]一个序列$a_1,...,a_n$合法当且仅当它们都是[1,A]中的数字且互不相同,一个序列的价值定义为数字的乘积,求所有序列的价值和.n<=500,A<=10^9,n+1< ...

  9. 【数据库】SQL经典面试题 - 数据库查询 - 子查询应用二

    上节课我们通过子查询,完成了查询的最高分学生的需求,今天我们来学习子查询的分类,以及通过子查询来完成工作中经常遇到一些个性化需求. 子查询概念: 一个SELECT语句嵌套在另一个SELECT语句中,子 ...

  10. const与指针

    C++中const与指针 1.常指针: ; int * const pInt = &x; 其中PInt是常指针,pInt的值无法改变,但其指向的内容可以改变. 2.指向常量的指针 有两种写法: ...