本文主要内容
- MongoDB基础操作命令示例练习
- MongoDB居于GridFSTemplate的文件上传、下载、删除等操作(工作重点使用)
1. 基础命令
创建的数据库名称:horse,创建的集合名称:blog
# 创建数据库
use horse
# 删除当前数据库[horse]
db.dropDatebase()
# 查看所有数据库
show dbs
# 设置用户的角色和权限
db.createUser({user:"horse",pwd:"mongo123",roles:[{role:"readWrite",db:"horse"}]})
# 创建指定名称的集合
db.createCollection("blog")
# 删除指定名称集合
db.blog.drop()
# 查看当前数据库[horse]中所有集合
show collections
# 插入文档
db.blog.insert({"name":"Tom","age":23,"sex":true})
db.blog.insertOne({"name":"Top","age":20,"sex":true})
db.blog.insertMany([{"name":"Jerry","age":22,"sex":false},{"name":"Free","age":21,"sex":true}])
# 更新文档
db.blog.update({"name":"Top"},{$set:{"name":"TopSun"}},{multi:true})
# 删除文档
db.blog.remove({"sex":false}, true)
db.blog.deleteMany({"age":23})
db.blog.deleteOne({"age":22})
# 删除集合所有数据
db.blog.deleteMan({})
# 查询文档
db.blog.find().pretty() # 通过查询方式(没有条件,查询所有)
db.blog.findOne({"name":"Tom"}) # 查询一个
db.blog.find({"age":{$lt: 23},"name":"Free"}).pretty() # 默认and连接查询
db.blog.find({$or:[{"age":{$lt:23}},{"name":"Free"}]}).pretty() # or连接查询
db.blog.find({"age":{$lt:23},$or:[{"name":"Free"},{"sex":"false"}]}).pretty() # and和or联合使用查询
db.blog.find().limit(2).skip(1).sort({"age":1}).pretty() # limit、skip、sort联合使用(执行顺序:sort-> skip ->limit)
# 聚合查询(参考文档)
db.blog.aggregate([{$group:{_id:"$age",count:{$sum:1}}}])
2. GridFsTemplate使用
2.1引入pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2.2 配置yml
spring:
data:
mongodb:
host: *.*.*.*
username: ***
password: ***
database: ***
port: 27017
# 设置文件上传的大小限制
servlet:
multipart:
max-file-size: 10MB
max-request-size: 50MB
2.3 上传下载删除
面对疾风吧:接合HuTool工具包食用更佳!!!
@Validated
@Controller
@RequestMapping("/mongo")
public class MongoUploadController {
private static Logger logger = LoggerFactory.getLogger(MongoUploadController.class);
@Autowired
private GridFsTemplate gridFsTemplate;
@Autowired
private MongoTemplate mongoTemplate;
private static final List<String> CONTENT_TYPES = Arrays.asList("image/gif", "image/jpeg", "image/jpg", "image/png");
@PostMapping("/upload")
public ResponseEntity<String> fileUpload(@RequestParam("file") MultipartFile file) {
try {
// 校验文件信息(文件类型,文件内容)
String originalFilename = file.getOriginalFilename();
if (StrUtil.isBlank(originalFilename)) {
return ResponseEntity.badRequest().body("参数错误");
}
String contentType = file.getContentType();
if (!CONTENT_TYPES.contains(contentType)) {
return ResponseEntity.badRequest().body("文件类型错误");
}
InputStream inputStream = file.getInputStream();
BufferedImage bufferedImage = ImageIO.read(inputStream);
if (ObjectUtil.isEmpty(bufferedImage)) {
return ResponseEntity.badRequest().body("文件内容错误");
}
// 文件重命名
String suffix = FileNameUtil.getSuffix(originalFilename);
String fileName = IdUtil.simpleUUID().concat(".").concat(suffix);
// 文件上传,返回ObjectId
ObjectId objectId = gridFsTemplate.store(inputStream, fileName, contentType);
return StrUtil.isBlank(String.valueOf(objectId)) ? ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上传失败") : ResponseEntity.ok(String.valueOf(objectId));
} catch (IOException e) {
return ResponseEntity.badRequest().body("文件上传异常");
}
}
@GetMapping("/read")
public void queryFileByObjectId(@RequestParam("objectId") @NotBlank(message = "ObjectId不能为空") String objectId, HttpServletResponse response) {
// 根据objectId查询文件
GridFSFile file = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(objectId)));
// 创建一个文件桶
GridFSBucket gridFsBucket = GridFSBuckets.create(mongoTemplate.getDb());
InputStream inputStream = null;
OutputStream outputStream = null;
try {
if (ObjectUtil.isNotNull(file)) {
// 打开下载流对象
GridFSDownloadStream fileStream = gridFsBucket.openDownloadStream(file.getObjectId());
// 创建girdFsResource,传入下载流对象,获取流对象
GridFsResource gridFsResource = new GridFsResource(file, fileStream);
// 写入输出流
inputStream = gridFsResource.getInputStream();
outputStream = response.getOutputStream();
byte[] bytes = new byte[1024];
if (inputStream.read(bytes) != -1) {
outputStream.write(bytes);
}
}
} catch (IOException e) {
logger.error("文件读取异常: {}", e.getMessage());
} finally {
IoUtil.close(outputStream);
IoUtil.close(inputStream);
}
}
@DeleteMapping("/remove")
public ResponseEntity<String> removeFileByObjectId(@RequestParam("objectId") @NotBlank(message = "ObjectId不能为空") String objectId) {
gridFsTemplate.delete(new Query(Criteria.where("_id").is(objectId)));
return ResponseEntity.ok("删除成功");
}
}
如果需要实现在浏览器页面下载此资源的功能,可结合js进行操作(文件类型根据具体业务需求而定)。主要实现代码如下所示:
downloadNotes(noteId) {
axios({
url: this.BASE_API + '/admin/mongo/file/query/' + noteId,
method: 'get',
responseType: 'arraybuffer',
params: { type: 'download' }
}).then(res => {
// type类型可以设置为文本类型,这里是pdf类型
const pdfUrl = window.URL.createObjectURL(new Blob([res.data], { type: `application/pdf` }))
const fname = noteId // 下载文件的名字
const link = document.createElement('a')
link.href = pdfUrl
link.setAttribute('download', fname)
document.body.appendChild(link)
link.click()
URL.revokeObjectURL(pdfUrl) // 释放URL 对象
})
}
以上就是SpringBoot整合MongoDB实现文件上传下载删除的详细内容,更多关于SpringBoot整合MongoDB的资料请关注编程网其它相关文章!