package MongoTest;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
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 java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* Created by liu on 2017-9-8.
*/
public class MogoUp {
public static void main(String[] args) throws IOException {
//连接MongoDB
//连接数据库
List<Document> list = new ArrayList<Document>();
// 连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
// ServerAddress()两个参数分别为 服务器地址 和 端口
ServerAddress serverAddress = new ServerAddress("169.254.123.90", 27017);
List<ServerAddress> addrs = new ArrayList<ServerAddress>();
addrs.add(serverAddress);
MongoCredential credential = MongoCredential.createScramSha1Credential("sa", "admin", "xush".toCharArray());
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(credential);
MongoClient client = new MongoClient(addrs, credentials);
//链接测试
MongoDatabase db = client.getDatabase("lhc");
MongoCollection<Document> coll = db.getCollection("test");
//上传文件
InputStream in = null;
String FileName = "C:\\Users\\liu\\Desktop\\CREC2010.svg";
File file = new File(FileName);
String fileName = file.getName();
String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
in = new FileInputStream(file);
GridFSBucket bucket = GridFSBuckets.create(db);
GridFSUploadOptions options = new GridFSUploadOptions();
//设置去除fileName之外的其他信息
Document metadata = new Document();
metadata.append("contentType", fileType);
options.metadata(metadata);
ObjectId objectId = bucket.uploadFromStream(fileName, in, options);
System.out.println(objectId);
System.out.println("上传成功");
//文件下载
OutputStream os = null;
String files = "C:\\Users\\liu\\Desktop\\CREC209.svg";
File file2 = new File(files);
if (!file2.exists()) {
file2.createNewFile();
}
os = new FileOutputStream(file2);
GridFSBucket bucket3 = GridFSBuckets.create(db);
// bucket3.downloadToStream(new ObjectId(objectId.toString()),os); //根据ObjectID
bucket3.downloadToStream(fileName, os); //根据文件名
System.out.println("下载成功");
}
}
java MongoDB上传下载(图片,txt等大文件)
5星 · 超过95%的资源 需积分: 49 179 浏览量
2017-09-08
17:43:04
上传
评论
收藏 1.57MB ZIP 举报
xiaoliuchangzai
- 粉丝: 10
- 资源: 14
最新资源
- 王锐的《OpenSceneGraph 3.0 Beginner's Guide》中文翻译版,个人读了翻译的很不错!值得推荐
- scr ubuntu上传
- AI Python编程学习课件-第6章深度学习
- STM32单片机FPGA毕设电路原理论文报告液晶显示模块与8031单片机的接口电路及编程
- STM32单片机FPGA毕设电路原理论文报告液晶航向指示器接口电路设计
- Pytorch深度学习入门与实战2024
- STM32单片机FPGA毕设电路原理论文报告野战救护车手术台稳定液压系统及其自动控制
- STM32单片机FPGA毕设电路原理论文报告压延机卷取调速装置改造
- STM32单片机FPGA毕设电路原理论文报告形状记忆合金驱动的微电脑密码锁的设计
- HTML小游戏27 - Chuck Chicken 魔法蛋网页游戏源码
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈