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 ...
随机推荐
- C++中的空类,编译器默认可以产生哪些成员函数
C++中的空类,编译器默认可以产生哪些成员函数 C++中创建一个空类:class Empty {};默认会生成4个函数,其函数的原型如下: public: Empty() { ... } Empty( ...
- insert tp5.1
$insertId = Db::name('user_address')->insertGetId($data); 会插入数据,返回插入的 id //$flag = Db::name('user ...
- T48566 【zzy】yyy点餐
T48566 [zzy]yyy点餐 题目描述 yyy去麦肯士吃垃圾食品. 麦肯士有n种单点餐品(汉堡薯条鸡翅之类的).每次选择一种或者以上的餐点,且每种餐点不多于一个的话,可以认为是购买套餐.购买一个 ...
- day4 数组学习
java提供的数组排序操作:java.util.Arrays.sort(数组名): java提供的数组复制:system.arraycopy(源数组名称,源数组开始点下标,目标数组名称,目标数组开始下 ...
- np.repeat函数
np.repeat用法 觉得有用的话,欢迎一起讨论相互学习~Follow Me np.repeat用于将numpy数组重复 一维数组重复三次 import numpy as np # 随机生成[0,5 ...
- webapi框架搭建-数据访问ef code first
webapi框架搭建系列博客 为什么用ef? 我相信很多博友和我一样都有这种“选择困难症”,我曾经有,现在也有,这是技术人的一个通病——总想用“更完美”的方式去实现,导致在技术选择上犹豫不决,或总是推 ...
- bzoj千题计划119:bzoj1029: [JSOI2007]建筑抢修
http://www.lydsy.com/JudgeOnline/problem.php?id=1029 把任务按截止时间从小到大排序 如果当前时间+当前任务耗时<=当前任务截止时间,把这个任务 ...
- Git之简介及安装
简介 Git是一个分布式版本控制系统,GitHub相当于一个远程仓库,注册账号可免费获得Git远程仓库. GitHub使用参考:https://guides.github.com/activities ...
- 把一个IEEE754浮点数转换为IBM370浮点数的C#代码
把一个IEEE754浮点数转换为IBM370浮点数的C#代码. 在这个网页上有古老的IBM370浮点格式的说明. // http://en.wikipedia.org/wiki/IBM_Floatin ...
- 【Codeforces858F】Wizard's Tour [构造]
Wizard's Tour Time Limit: 50 Sec Memory Limit: 512 MB Description Input Output Sample Input 4 5 1 2 ...