Java MongoDB : Save image example
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的更多相关文章
- Java + MongoDB Hello World Example--转载
原文地址:http://www.mkyong.com/mongodb/java-mongodb-hello-world-example/ A simple Java + MongoDB hello w ...
- 【MongoDB数据库】Java MongoDB CRUD Example
上一页告诉我们MongoDB 命令入门初探,本篇blog将基于上一篇blog所建立的数据库和表完毕一个简单的Java MongoDB CRUD Example.利用Java连接MongoDB数据库,并 ...
- java MongoDB查询(二)复杂查询
前言 在上篇<java MongoDB查询(一)简单查询>中我们简单了解了下查询,但是仅仅有那些查询是不够用的,还需要复杂的查询,这篇就这点进行叙述. 1.数据结构 集合:firstCol ...
- MongoDB save()方法和insert()方法的区别
MongoDB save()方法和insert()方法的区别 首先看官方文档怎么说的 Updates an existing document or inserts a new document, d ...
- Java mongodb api疑问之MongoCollection与DBCollection
在学习Java mongodb api时发现,可以调用不同的java mongodb api来连接数据库并进行相关操作. 方式一: 该方式使用mongoClient.getDB("xxx&q ...
- Java MongoDB插入
前言 插入是向MongoDB中添加数据的基本方法.对目标集使用insert方法来插入一条文档.这个方法会给文档增加一个”_id”属性(如果原来没有的话),然后保存到数据库中. 1.连接数据库,拿到集合 ...
- java mongodb 增删改查 工具类
package com.jttx.demo; import com.mongodb.*; import com.mongodb.util.JSON; import java.net.Unkno ...
- java mongoDB 二级数组嵌套查询
场景: 会员集合下有多个会员文档,会员文档下有多个订单文档,订单买了多个商品文档 member->orders>orderItems 要求: 通过会员id和商品id验证会员是否购买过该商品 ...
- Java MongoDB Driver 3.x - Quick Start
Maven Dependency: <dependency> <groupId>org.mongodb</groupId> <artifactId>mo ...
随机推荐
- Error: cannot allocate vector of size 88.1 Mb问题
这几天训练模型运行代码的时候,老是提示我说:Error: cannot allocate vector of size 88.1 Mb,只知道分配空间不足. 下面是查资料看到的一些回答: 一.这个是R ...
- radio 控制器function用法
delivery_show(); $('.delivery_btn').on('click',function(){ delivery_show(); }); function delivery_sh ...
- P3014 [USACO11FEB]牛线Cow Line && 康托展开
康托展开 康托展开为全排列到一个自然数的映射, 空间压缩效率很高. 简单来说, 康托展开就是一个全排列在所有此序列全排列字典序中的第 \(k\) 大, 这个 \(k\) 即是次全排列的康托展开. 康托 ...
- 关于Linux用户名
1.创建/删除/修改用户名 useradd 选项 用户名其中各选项含义如下: 代码:-c comment 指定一段注释性描述.-d 目录 指定用户主目录,如果此目录不存在,则同时使用-m选项,可以创建 ...
- webpack的基础入门
webpack的基础入门 这里对于 webpack 的基础入门进行一些总结,可以参考 github 上的 webpack-demo ,链接是 https://github.com/RealAndMe/ ...
- 数据结构编程实验——chapter9-应用二叉树的基本概念编程
二叉树是树结构中的重要概念,一些特殊的二叉树如满二叉树和完全二叉树由于节点序号的特殊关系,在一些算法中十分常见. 这篇文章将从三个方面介绍有关二叉树的知识点: (1) 普通有序树转化为二叉树. ( ...
- Django 2.0.1 官方文档翻译: 编写你的第一个 Django app,第三部分(Page 8)
编写你的第一个 Django app,第三部分(Page 8)转载请注明链接地址 本页教程接前面的第二部分.我们继续开发 web-poll app,我们会专注于创建公共接口上 -- "视图& ...
- Java并发编程原理与实战三十:CountDownLatch与CyclicBarrier 区别
相信每个想深入了解多线程开发的Java开发者都会遇到CountDownLatch和CyclicBarrier,大家也在网上看到各种介绍原理,代码的,以及他们区别(应付面试)的,但是很少能讲清楚:他们到 ...
- 从github上下载一个csv文件
when u open the raw file(i.e. csv) on github, then point to RAW button, then right click the mouse, ...
- AngularJS 、Backbone.js 和 Ember.js 的比较
1 介绍 我们准备在这篇文章中比较三款流行于Web的“模型-视图-*”框架:AngularJS.Backbone和Ember.为你的项目选择正确的框架能够对你及时交付项目的能力和在以后维护你自己代码的 ...