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请求:

Java操作Mongodb之文件读写_第1张图片


去Mongo里面查看(楼主这里用的是MongoBooster客户端):

Java操作Mongodb之文件读写_第2张图片


根据查询参数,从Mongodb下载图片:

Java操作Mongodb之文件读写_第3张图片



根据查询参数,删除Mongodb图片:

Java操作Mongodb之文件读写_第4张图片


可以在Mongodb里面看到,代表文件的那一条数据已经被删除了:

Java操作Mongodb之文件读写_第5张图片




你可能感兴趣的:(数据库)