import com.mongodb.DB; import com.mongodb.gridfs.GridFS; import com.mongodb.gridfs.GridFSDBFile; import com.mongodb.gridfs.GridFSInputFile; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.MongoDbFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody;
@Autowired
private MongoDbFactory mongoDbFactory;
// 上传
@GetMapping("saveFile")
public @ResponseBody String
saveFile(){
try {
// File file = new File("D://out.txt");
File file = new File("D://bb.doc");
DB db = mongoDbFactory.getLegacyDb();
// 存储fs的根节点
GridFS gridFS = new GridFS(db, "aaaa");
GridFSInputFile gfs = gridFS.createFile(file);
gfs.put("aliases", "2222");
gfs.put("filename", "bb.doc");
gfs.put("contentType", "txt");
gfs.save();
} catch (IOException e) {
e.printStackTrace();
}
return "ok";
}
//查看 (下载 需要设置 response 的http 响应头 )
@GetMapping("catFile")
public void
catFile(HttpServletResponse response){
try {
DB db = mongoDbFactory.getLegacyDb();
// 获取fs的根节点
GridFS gridFS = new GridFS(db, "aaaa");
GridFSDBFile dbfile = gridFS.findOne("bb.doc");
dbfile.writeTo(response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
zegoto.cn