SpringBoot整合MongoDB实现文件上传下载删除

网友投稿 684 2023-01-23

SpringBoot整合MongoDB实现文件上传-删除

SpringBoot整合MongoDB实现文件上传-删除

本文主要内容

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().phttp://retty() # 通过查询方式(没有条件,查询所有)

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依赖

org.springframework.boot

spring-boot-starter-data-mongodb

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工具包食用更佳!!!

/**

* @author Mr.Horse

* @version 1.0

* @description: MongoDB的文件上传、-、删除等基本操作(集合HuTool工具库)

* @date 2021/4/29 9:53

*/

@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 CONTENT_TYPES = Arrays.asList("image/gif", "image/jpeg", "image/jpg", "image/png");

/**

* MongoDB文件上传(图片上传)

*

* @param file

* @return

*/

@PostMapping("/upload")

public ResponseEntity fileUpload(@RequestParam("file") MultipartFile file) {

try {

// 校验文件信息(文件类型,文件内容)

aFwChW 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("文件上传异常");

}

}

/**

* 根据ObjectId读取文件并写入响应流,页面进行进行相关操作,可以进行文件的-和展示

*

* @param objectId

*/

@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);

}

}

/**

* 根据ObjectId删除文件

*

* @param objectId

* @return

*/

@DeleteMapping("/remove")

public ResponseEntity 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的资料请关注我们其它相关文章!

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:跨平台混合app开发(跨平台APP开发)
下一篇:通软应用安全桌面注册(通软桌面管理)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~