GridFS文件存储

使用命令行操作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();
// }
//
// }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值