mongodb文件上传下载删除查询

在mongo-java-driver3.x以上的版本中逐渐弃用了Mongo和getDB等一系列方法,所以原来的GridFS的用法也发生了一些改变
改进前:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;
public class GridTest {

private static final Logger log = LoggerFactory.getLogger(GridTest.class); public static void main(String[] args) throws FileNotFoundException{ // 连接到 mongodb 服务 @SuppressWarnings("resource") MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); @SuppressWarnings("deprecation") DB db = mongoClient.getDB("test"); log.info("成功连接数据库"); String collectionName="mongoCollectionTest"; GridFS gridFS = new GridFS(db,collectionName); /* * 2、上传文件 */ //创建测试文件,mongo 默认存在该文件 File file=new File("E:-----------.pdf"); FileInputStream fileInputStream=new FileInputStream(file); //创建gridFS文件数据流 GridFSInputFile createFile=gridFS.createFile(fileInputStream); //设置文件属性 createFile.put("filename", "123.pdf"); createFile.put("contentType", "application/pdf"); createFile.save(); /* * 3、根据id查询上传文件 */ GridFSDBFile findOne= gridFS.findOne(new BasicDBObject("_id",createFile.getId())); System.out.print(findOne); }

}
改进后:
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import com.mongodb.client.gridfs.model.GridFSUploadOptions;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.UUID;
public class MongoDBTest {
private static Logger log = LoggerFactory.getLogger(MongoDbUtil.class);
private static final class MongoInstance { public final static MongoClient client; static { client = new MongoClient("localhost", 27017); } }public static MongoDatabase getDatabase(String databaseName) { return MongoInstance.client.getDatabase(databaseName); }/** * 上传文件 * @param file * @param databaseName * @return */ public static String uploadFileToGridFS(File file,String databaseName) { InputStream in = null; String returnId = null; String pathName = file.getPath(); String[] pathNameArray = pathName.split("\\\\"); String[] name = pathNameArray[pathNameArray.length-1].split("\\."); String filename = name[0]; String type = name[name.length-1]; try { in = new FileInputStream(file); GridFSBucket bucket = GridFSBuckets.create(getDatabase(databaseName)); GridFSUploadOptions options = new GridFSUploadOptions(); //设置除filename以为的其他信息 Document metadata = https://www.it610.com/article/new Document(); metadata.append("contentType", type); options.metadata(metadata); ObjectId fileId = bucket.uploadFromStream(filename+type, in,options); returnId = fileId.toHexString(); log.info("文件上传成功"); } catch (IOException e) { log.info("upload fail:" + e); } finally { try { in.close(); } catch (IOException e) { log.info("close inputstream fail:" + e); } } return returnId; }/** * 通过objectid和file下载文件 * @param objectId * @param file * @param databaseName */ public static void downloadFile(String objectId, File file,String databaseName) { OutputStream os = null; try { os = new FileOutputStream(file); GridFSBucket bucket = GridFSBuckets.create(getDatabase(databaseName)); bucket.downloadToStream(new ObjectId(objectId), os); log.info("文件下载成功"); } catch (IOException e) { log.info("download fail:" + e); } finally { if (os != null) { try { os.close(); } catch (IOException e) { log.info("close outputstream fail:" + e); } } } }/** * 通过objectid删除文件 * @param objectId * @param databaseName */ public static void deleteByObjectId(String objectId,String databaseName) { GridFSBucket bucket = GridFSBuckets.create(getDatabase(databaseName)); bucket.delete(new ObjectId(objectId)); log.info("文件删除成功"); }/** * 查询文件 * @param databaseName */ public static List find(String databaseName){ GridFSBucket bucket = GridFSBuckets.create(getDatabase(databaseName)); GridFSFindIterable iterable = bucket.find(); MongoCursor mongoCursor= iterable.iterator(); List results = new ArrayList(); while(mongoCursor.hasNext()){ results.add(mongoCursor.next()); } return results; }/** * 查询文件 * @param databaseName */ public static List findBy(String databaseName,Bson filter){ GridFSBucket bucket = GridFSBuckets.create(getDatabase(databaseName)); GridFSFindIterable iterable = bucket.find(filter); MongoCursor mongoCursor= iterable.iterator(); List results = new ArrayList(); while(mongoCursor.hasNext()){ results.add(mongoCursor.next()); } return results; }

}
import java.io.File;
import org.junit.Test;
public class MongoGridFSTest
{
/** * 先上传 */ @Test public void upload() { File file = new File("C:/Users/Administrator/Desktop/Java持久化之myBatis3.pdf"); String databaseName = "test"; String objectId = MongoDbFSUtil.uploadFileToGridFS(file,databaseName); System.out.println(objectId); System.out.println("文件上传成功"); }/** * 测试下载 */ @Test public void download() { //System.out.println(objectId); File file = new File("D:/1.pdf"); String databaseName = "test"; MongoDbFSUtil.downloadFile("594b8298932ed623249dea18", file,databaseName); System.out.println("文件下载成功"); }/** * 最后将上传的信息删除 */ @Test public void delete() { String databaseName = "test"; MongoDbFSUtil.deleteByObjectId("594b3b53932ed60b043ac4c8",databaseName); } @Test public void find(){ List results= MongoDbFSUtil.find("test"); for(GridFSFile file: results){ System.out.println(file.toString()); } }@Test public void findBy(){ Document filter = new Document(); filter.append("filename", "深入理解Java虚拟机:JVM高级特性与最佳实践.pdf"); List results= MongoDbFSUtil.findBy("test",filter); for(GridFSFile file: results){ System.out.println(file.getId()); } }

【mongodb文件上传下载删除查询】}

    推荐阅读