java mongodb 读取文件_Java操作Mongodb之文件读写
Maven依赖:
org.mongodb.morphia
morphia
1.1.0
mongo-java-driver
org.mongodb
mongo-java-driver
org.mongodb
3.0.2
**Controller.java中的Mapping映射:
@RequestMapping(value = "/uploadFileToMongo")
public JSONMessage uploadFileToMongo(MultipartFile file, String id, String filename, String collection){
if (file != null && file.getName() != null && !file.isEmpty()) {
byte[] bytes=null;
try {
bytes = file.getBytes();
} catch (IOException e) {
e.printStackTrace();
}
MongoFileOperationUtil.saveFile(bytes ,id, filename, collection);
return JSONMessage.success();
} else {
return JSONMessage.failure("上传文件为空!");
}
}
@RequestMapping(value = "/downloadFileFromMongo")
public JSONMessage downloadFileFromMongo(String id, String filename, String collection, String contentType) {
try {
response.setHeader("Content-Disposition", "attachment;fileName=" + filename);
InputStream inputStream = MongoFileOperationUtil.readFile(id, filename, collection, contentType);
OutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
os.close();
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return JSONMessage.success();
}
@RequestMapping(value = "/removeFileFromMongo")
public JSONMessage removeFileFromMongo(String id, String filename, String collection, String contentType) {
try {
MongoFileOperationUtil.removeFile(id, filename, collection, contentType);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return JSONMessage.success();
}
MongoFileOperationUtil是自己封装的一个工具类:
@Component
public class MongoFileOperationUtil {
private static AdvancedDatastore dsForRW;
private static final Logger log = LoggerFactory.getLogger(MongoFileOperationUtil.class);
@Autowired
public void setDatastore(AdvancedDatastore dsForRW) {
MongoFileOperationUtil.dsForRW = dsForRW;
}
public static void saveFile(File file, String id, String collection) {
if (!file.exists()) {
throw new ServiceException("文件没有找到");
}
try {
// 连接数据库
DB db = dsForRW.getDB();
// 文件操作是在DB的基础上实现的,与表和文档没有关系
GridFS gridFS = null;
gridFS = new GridFS(db);
GridFSInputFile mongofile = gridFS.createFile(file);
// 添加属性
if (id != null) {
mongofile.put("_id", id);// 对应id
}
String filename=file.getName();
if (filename != null) {
mongofile.put("filename", filename);// 文件名称
if (filename.lastIndexOf(".") > 0) {
mongofile.put("contentType", filename.substring(filename.lastIndexOf(".") + 1));// 文件类型
}
}
if (collection != null) {
mongofile.put("collection", collection);// 所属集合
}
mongofile.save();// 保存
} catch (Exception e) {
e.printStackTrace();
log.info("存储文件异常,id:" + id + ",所属集合:" + collection);
}
}
public static void saveFile(byte[] data, String id, String filename, String collection) {
if (data == null || data.length == 0) {
throw new ServiceException("bytes不能为空");
}
try {
// 连接数据库
DB db = dsForRW.getDB();
// 文件操作是在DB的基础上实现的,与表和文档没有关系
GridFS gridFS = null;
gridFS = new GridFS(db);
GridFSInputFile mongofile = gridFS.createFile(data);
// 添加属性
if (id != null) {
mongofile.put("_id", id);// 对应id
}
if (filename != null) {
mongofile.put("filename", filename);// 文件名称
if (filename.lastIndexOf(".") > 0) {
mongofile.put("contentType", filename.substring(filename.lastIndexOf(".") + 1));// 文件类型
}
}
if (collection != null) {
mongofile.put("collection", collection);// 所属集合
}
mongofile.save();// 保存
} catch (Exception e) {
e.printStackTrace();
log.info("存储文件异常,id:" + id + ",所属集合:" + collection);
}
}
public static InputStream readFile(String id, String filename, String collection, String contentType)
throws Exception {
// 连接数据库
DB db = dsForRW.getDB();
GridFS gridFs = null;
gridFs = new GridFS(db);
// 查找条件
DBObject query = new BasicDBObject();
if (id != null) {
query.put("_id", id);
}
if (filename != null) {
query.put("filename", filename);
}
if (collection != null) {
query.put("collection", collection);
}
if (contentType != null) {
query.put("contentType", contentType);
}
// 查询的结果
GridFSDBFile gridDBFile = gridFs.findOne(query);
// 返回字节流
return gridDBFile.getInputStream();
}
public static void removeFile(String id, String filename, String collection, String contentType) throws Exception {
// 连接数据库
DB db = dsForRW.getDB();
GridFS gridFs = null;
gridFs = new GridFS(db);
// 查找条件
DBObject query = new BasicDBObject();
if (id != null) {
query.put("_id", id);
}
if (filename != null) {
query.put("filename", filename);
}
if (collection != null) {
query.put("collection", collection);
}
if (contentType != null) {
query.put("contentType", contentType);
}
gridFs.remove(query);
}
}
这里用Postman模拟上传文件的Post请求:
去Mongo里面查看(楼主这里用的是MongoBooster客户端):
根据查询参数,从Mongodb下载图片:
根据查询参数,删除Mongodb图片:
可以在Mongodb里面看到,代表文件的那一条数据已经被删除了:
java mongodb 读取文件_Java操作Mongodb之文件读写相关推荐
- java mongodb 模糊查询_Java操作MongoDB插入数据进行模糊查询与in查询功能的方法
Java操作MongoDB插入数据进行模糊查询与in查询功能 由于需要用MongoDB缓存数据,所以自己写了一套公共的存放和读取方法 具体如下: 存放mongodb: /** * 公共方法:设置Obj ...
- java操作mongodb查询总数_java操作mongodb——查询数据
field为查询字段,value为查询值,也可以通过过滤器Filters,Filters提供了一系列查询条件的静态方法 相等 - = FindIterable iter = doc.find(new ...
- java mongodb条件查询_java 操作mongodb查询条件的常用设置
java操作mongodb进行查询,常用筛选条件的设置如下: 条件列表: BasicDBList condList = new BasicDBList(); 临时条件对象: BasicDBObject ...
- java mongodb排序查询_java操作mongodb基础(查询 排序 输出list)
代码如下: package com.infomorrow.webroot; import java.util.List; import com.mongodb.BasicDBObject; impor ...
- python简述文件的操作步骤_Python文件读取操作的详细介绍
本篇文章给大家带来的内容是关于Python文件读取操作的详细介绍,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助. 读取文件的操作步骤 有一道脑筋急转弯,问把大象装进冰箱的步骤,答案很简 ...
- java mongodb 增删改查_java操作mongodb:基本的增删改查
java操作mongodb的代码,包含基本的增删改查操作 获取数据库连接工具类 package com.liuc.db;import java.net.UnknownHostException;imp ...
- java 连接mongodb 集群_Java 连接MongoDB集群的几种方式
先决条件 先运行mongodb肯定是必须的,然后导入以下包: import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; im ...
- mongodb java连接 集群_java连接mongodb集群
MongoDb 的分片拓展与副本集 Mongodb 数据库分片是通过并行处理数据实现负载均衡的一种重要手段[12],同时也是数据库集群 实现分布式计算的关键技术.在生产环境中,...... 本地数据访 ...
- java properties读取缓存_java 读取 properties文件的各种方法
1.使用java.util.Properties类的load()方法 示例: InputStream in = lnew BufferedInputStream(new FileInputStream ...
- java object取数据_java使用ObjectInputStream从文件中读取对象
import java.io.EOFException; import java.io.FileInputStream; import java.io.FileNotFoundException; i ...
最新文章
- html5考试总结300字,期中考心得300字5
- 基于BASYS2的VHDL程序——交通灯(状态机版)
- 虚拟机登服务器,用虚拟机登录云服务器
- MySQL 5.7 新特性详解
- es5如何实现promise_彻底理解Promise对象——用es5语法实现一个自己的Promise(上篇)...
- TortoiseSVN与VisualSVN Server搭建SVN版本控制系统【转】
- java poi excel 生成表格的工具封装
- 堆的定义与操作(C语言)
- 异步fifo_【推荐】数字芯片异步FIFO设计经典论文
- 漫步数理统计十五——两个随机变量的分布
- 跨server传输数据注意事项
- SDL2源代码分析3:渲染器(SDL_Renderer)
- Atitit webdav 的问题 -------------大文件传输问题 在某些版本的 Windows 操作系统中,WebDAV 驱动器的最大文件大小被限制为 50MB。如果你试图复制超过 5
- html页面怎么加入qq群,qq群申请
- 基于LabWindows/CVI学生管理系统的实现
- 区分微信开发平台和公众平台(小程序)
- cobble服务器安装配置
- 图扑数字孪生军演,构建跨域作战体系
- stm32中常见的通信协议之SPI
- codeforces 848E. Days of Floral Colours
热门文章
- imooc数据结构探险-栈篇 栈应用括号匹配二 由群友启发改良james_yuan老师算法
- java基础 (六)面向对象(一)
- 【转】Nutch源代码研究 网页抓取 数据结构
- 神经网络动态可视化工具
- 第11章 支撑向量机 SVM 学习笔记 下 高斯核函数RBF
- 190216每日一句
- Atiitt 流水线停顿问题与解决方法 1. 流水线技术方式分类	1 2. 但在实际中,会出现2种情况使流水线停顿下来或不能启动:	2 2.1. 1、多个任务在同一时间周期内争用同一个流水段	2 2
- Atitit 人工智能目前的进展与未来 包含的技术 v3
- Atitit dsl对于数组的处理以及main函数的参数赋值
- Atitit.提升稳定性-----分析内存泄漏PermGen OOM跟解决之道...java