使用命令行操作GridFS
1.上传文件
2.切换到mongo,查看文件信息
3.1查看块信息
分块数目 11个 = 2670592 / 261120 向上取整
3.2 查看块内容
db.fs.chunks.find({files_id:ObjectId(“607e54f52db02c2b6bf3c12a”)})
4.切换到c盘用户路径下,下载文件
Java访问GirdFS
首先在libs中添加mongo-driver.jar包 右键add to build path
之后再写代码 测试文件的上传和下载
package cn.gdco;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.bson.Document;
import org.bson.types.ObjectId;
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;
public class Main2 {
public static void main(String[] args) {
//uploadFile();
downloadFile();
}
//
//
// //下载文件
private static void downloadFile() {
MongoClient mongoClient = new MongoClient();
MongoDatabase myDataBase = mongoClient.getDatabase("gridfs");
GridFSBucket gridFSBucket = GridFSBuckets.create(myDataBase);
try {
FileOutputStream outputStream = new FileOutputStream("C:\\Users\\HXD\\Desktop\\GridFS存储下载.ppt");
ObjectId id = new ObjectId("607eebeb22df0f110c75ade0");
gridFSBucket.downloadToStream(id, outputStream);
outputStream.flush();
outputStream.close();
System.out.println("下载成功");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// 上传文件
// private static void uploadFile() {
// MongoClient mongoClient = new MongoClient();
// MongoDatabase myDataBase = mongoClient.getDatabase(“gridfs”);
// GridFSBucket gridFSBucket = GridFSBuckets.create(myDataBase);
//
// try {
// InputStream inputStream = new FileInputStream(“C:\Users\HXD\Desktop\GridFS存储.ppt”);
// GridFSUploadOptions options = new GridFSUploadOptions().chunkSizeBytes(2670592)
// .metadata(new Document(“type”, “ppt”));
// ObjectId id = gridFSBucket.uploadFromStream(“GridFS存储.ppt”, inputStream, options);
// System.out.println(“上传成功” + id.toString());
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
//
// }
}