以下是对于图片的一些基本操作:
1、存储图片
// 存储文件信息 GridFS gridFS = new GridFS(MongoDBUtil.getDB(), "test"); File localFile = new File("d://test.jpg"); GridFSInputFile oneFile = gridFS.createFile(localFile); oneFile.setFilename("test.jpg"); // 配置文件属性 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式 BasicDBObject metadata = new BasicDBObject(); metadata.put("uploadDate", df.format(new Date())); oneFile.setMetaData(metadata);//添加属性 oneFile.save();//保存文件
2、根据文件ID读取图片
// 存储文件信息 GridFS gridFS = new GridFS(MongoDBUtil.getDB(), "test"); // 读取文件 GridFSDBFile outFile = gridFS.findOne(new ObjectId(request.getParameter("id"))); //System.out.println(outFile);
3、根据MetaData属性查找图片
// GridFS gridFS = new GridFS(MongoDBUtil.getDB(), "test"); //查找条件 BasicDBObject query = new BasicDBObject("metadata.pkid", "1123"); List<GridFSDBFile> listFiles = gridFS.find(query); System.out.println(listFiles); System.out.println(listFiles.size());
4、显示图片
@RequestMapping(value = "/show") public void show(HttpServletRequest request, HttpServletResponse response){ try { OutputStream out = response.getOutputStream(); response.setContentType("image/jpg"); GridFS gridFS = new GridFS(MongoDBUtil.getDB(), "test"); // 读取文件 GridFSDBFile outFile = gridFS.findOne(new ObjectId(request.getParameter("id"))); //System.out.println(outFile); if(outFile!=null){ outFile.writeTo(out); out.flush(); out.close(); } } catch (Exception e) { e.printStackTrace(); } }