- 建立java项目
- 新建lib包,导入jar包
3.链接mongdo数据库代码
/**
* 1.获取连接
* 2.上传文件
* 3.下载文件
* 4.删除文件
*
*/
public static GridFS GetMongoGridFS(){
List<ServerAddress> adds = new ArrayList<>();
ServerAddress serverAddress = new ServerAddress("192.168.1.100", 27017);
adds.add(serverAddress);
List<MongoCredential> credentials = new ArrayList<>();
//MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
MongoCredential mongoCredential = MongoCredential.createScramSha1Credential("uname", "mg", "pw".toCharArray());
credentials.add(mongoCredential);
//通过连接认证获取MongoDB连接
MongoClient mongoClient = new MongoClient(adds,credentials);
//连接到数据库
DB mongoDatabase = mongoClient.getDB("testdb");
GridFS myFS = new GridFS(mongoDatabase);
return myFS;
}
上传文件
/**
* @return
* 上传文件
* @Title: UploadFile
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param: @param file
* @return: void
* @throws
*/
public String UploadFile(File file) {
try {
GridFS gridFS = GetMongoGridFS();
GridFSFile mgupfile = gridFS.createFile(file);
mgupfile.save();
return mgupfile.getId().toString();
} catch (Exception e) {
return null;
}
}
下载文件
/**
* 下载文件
* @Title: DownloadFile
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param: @param objectid
* @param: @return
* @return: String
* @throws
*/
public String DownloadFile(String objectid) {
try {
GridFS gridFS = GetMongoGridFS();
GridFSDBFile file2 =gridFS.findOne(new ObjectId(objectid));
String filename="D:/tmp/5"+file2.getFilename();
long writeTo = file2.writeTo(new File(filename));
if(writeTo>=0){
return filename;
}else{
return null;
}
} catch (Exception e) {
return null;
}
}
删除文件
/**
* 删除文件
* @Title: DeleteFile
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param: @param objectid
* @param: @return
* @return: String
* @throws
*/
public void DeleteFile(String objectid) {
GridFS gridFS = GetMongoGridFS();
GridFSDBFile file =gridFS.findOne(new ObjectId("5c4fed8064873a4a68427f93"));
gridFS.remove((ObjectId) file.getId());
}