java+MongoDB實現存圖片、下載圖片
阿新 • • 發佈:2018-12-22
1.存圖片
demo:將某個檔案存到mongoDB,這個file可以通過前臺引數傳入,我這裡直接將D://test.png存到mongoDB
@RequestMapping("/addFile") @ResponseBody public String addFile(){ MongoClient client = new MongoClient("127.0.0.1",27017); DB db = client.getDB("files"); GridFS fs = new GridFS(db); try { GridFSInputFile gridFSInputFile = fs.createFile(new File("D://test.png")); gridFSInputFile.setFilename("db_test.png"); gridFSInputFile.save(); } catch (IOException e) { e.printStackTrace(); } return "file over"; }
執行後,可看到圖片已經存入成功:
2.下載圖片
需要指定圖片id,可從前端引數傳入,我這裡寫死(上一步存圖片,對應了一個mongoDB中的files_id):
@RequestMapping("/downFile") public void downFile(HttpServletResponse response){ String fileId = "5c0f7c374fc404123403d69e";//這裡可以通過引數取代 try { MongoClient client = new MongoClient("127.0.0.1",27017); DB db = client.getDB("files"); GridFS fs = new GridFS(db); GridFSDBFile gridFSDBFile = fs.findOne(new ObjectId(fileId)); OutputStream sos = response.getOutputStream(); response.setContentType("application/octet-stream"); // 獲取原檔名 String name = (String) gridFSDBFile.get("filename"); String fileName = new String(name.getBytes("GBK"), "ISO8859-1"); // 設定下載檔名 response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // 向客戶端輸出檔案 gridFSDBFile.writeTo(sos); sos.flush(); sos.close(); } catch (IOException e) { e.printStackTrace(); } }