Spring Boot使用GridFS实现文件的上传和下载方式
更新时间:2021年10月23日 16:00 点击:2451 作者:我朋友说他好了
使用GridFS实现文件的上传和下载
在这篇博客中,我们将展示如何使用Spring Boot中使用mongodb自带的文件存储系统GridFS实现文件的上传和下载功能
首先了解一下怎么用命令操作GridFS
安装mongodb
sudo apt-get install mongodb
安装完成后找到mongofiles的位置
whereis mongofiles
找到之后进入目录就可以上传文件了
mongofiles put /home/ubuntu/Desktop/1.jpg
这时文件就添加成功了,进入mongodb查看
mongo show dbs # 发现多了一个gridfs use gridfs db.fs.files.find() # 存放文件的一些基本信息 db.fs.chunks.find() # 存放文件二进制内容,一个文件有多个fs.chunks,每个fs.chunks都有一个,files_id与fs.files中的id相对应,形成多对一的关系,文件存的时候分开存,取的时候再合并
使用Spring Boot操作GridFS
引入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency>
controller代码
import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import com.mongodb.client.gridfs.GridFSBucket; import com.mongodb.client.gridfs.GridFSDownloadStream; import com.mongodb.client.gridfs.GridFSFindIterable; import com.mongodb.client.gridfs.model.GridFSFile; import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.gridfs.GridFsOperations; import org.springframework.data.mongodb.gridfs.GridFsResource; import org.springframework.data.mongodb.gridfs.GridFsTemplate; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.io.InputStream; import static org.springframework.data.mongodb.core.query.Query.query; import static org.springframework.data.mongodb.gridfs.GridFsCriteria.whereFilename; @RestController public class ImageController { @Autowired private GridFsTemplate gridFsTemplate; @Autowired private GridFsOperations operations; @Autowired private GridFSBucket gridFSBucket; @PostMapping("file/upload") public ImageResponse upload(@RequestParam("file") MultipartFile file) { DBObject metaData = new BasicDBObject(); // 把时间戳作为文件名存入mongodb String fileName = String.valueOf(System.currentTimeMillis()); InputStream inputStream = null; try { inputStream = file.getInputStream(); gridFsTemplate.store(inputStream, fileName, "image", metaData); } catch (IOException e) { throw new RuntimeException(); } return new ImageResponse(fileName); } @GetMapping(value = "file/download/${fileName}", produces = MediaType.IMAGE_JPEG_VALUE) @ResponseBody public byte[] getImage(@PathVariable("fileName") String fileName) throws IOException { if (fileName == null) { return null; } // 根据文件名查询(也可以根据md5值等信息查询) GridFSFindIterable result = operations.find(query(whereFilename().is(fileName))); GridFSFile gridFSFile = result.first(); GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId()); //创建gridFsResource,用于获取流对象 GridFsResource gridFsResource = new GridFsResource(gridFSFile, gridFSDownloadStream); return IOUtils.toByteArray(gridFsResource.getInputStream()); } }
加入一个配置类
import com.mongodb.MongoClient; import com.mongodb.client.MongoDatabase; import com.mongodb.client.gridfs.GridFSBucket; import com.mongodb.client.gridfs.GridFSBuckets; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MongoConfig { @Value("${spring.data.mongodb.database}") String db; @Bean public GridFSBucket getGridFSBucket(MongoClient mongoClient){ MongoDatabase database = mongoClient.getDatabase(db); GridFSBucket bucket = GridFSBuckets.create(database); return bucket; } }
图片返回的实体类
public class ImageResponse implements Serializable { private String imageName; public ImageResponse(String imageName) { this.imageName = imageName; } public String getImageName() { return imageName; } public void setImageName(String imageName) { this.imageName = imageName; } }
配置文件
spring: data: mongodb: uri: mongodb://localhost:27017/gridfs database: gridfs
Spring Boot中使用GridFS
什么是GridFS
GirdFS是MongoDB提供的用于持久化存储文件的模块
在GridFS存储文件是将文件分块存储,文件会按照256KB的大小分割成多个块进行存储,GridFS使用两个集合 (collection)存储文件,一个集合是chunks, 用于存储文件的二进制数据;一个集合是files,用于存储文件的元数 据信息(文件名称、块大小、上传时间等信息)。
从GridFS中读取文件要对文件的各各块进行组装、合并。
在SpringBoot中使用GridFS
存储文件
@Autowired GridFsTemplate gridFsTemplate; @Test public void GridFsTest() throws FileNotFoundException { //选择要存储的文件 File file = new File("/Users/xxx/Desktop/xxx.docx"); InputStream inputStream = new FileInputStream(file); //存储文件并起名称 ObjectId objectId = gridFsTemplate.store(inputStream, "面试宝典"); String id = objectId.toString(); //获取到文件的id,可以从数据库中查找 System.out.println(id); }
查找文件
创建GridFSBucket对象
@Configuration public class MongoConfig { @Value("${spring.data.mongodb.database}") String db; @Bean public GridFSBucket getGridFSBucket(MongoClient mongoClient){ MongoDatabase mongoDatabase = mongoClient.getDatabase(db); GridFSBucket bucket = GridFSBuckets.create(mongoDatabase); return bucket; } }
@Autowired GridFsTemplate gridFsTemplate; @Autowired GridFSBucket gridFSBucket; @Test public void queryFile() throws IOException { String id = "5c1b8fac72884e389ae3df82"; //根据id查找文件 GridFSFile gridFSFile = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(id))); //打开下载流对象 GridFSDownloadStream gridFS = gridFSBucket.openDownloadStream(gridFSFile.getObjectId()); //创建gridFsSource,用于获取流对象 GridFsResource gridFsResource = new GridFsResource(gridFSFile,gridFS); //获取流中的数据 String string = IOUtils.toString(gridFsResource.getInputStream(), "UTF-8"); System.out.println(string); }
删除文件
//删除文件 @Test public void testDelFile() throws IOException { //根据文件id删除fs.files和fs.chunks中的记录 gridFsTemplate.delete(Query.query(Criteria.where("_id").is("5c1b8fac72884e389ae3df82"))); }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持猪先飞。
原文出处:https://blog.csdn.net/qq_44693282/article/details/97916541
相关文章
解决springboot使用logback日志出现LOG_PATH_IS_UNDEFINED文件夹的问题
这篇文章主要介绍了解决springboot使用logback日志出现LOG_PATH_IS_UNDEFINED文件夹的问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-04-28- 这篇文章主要介绍了C#实现HTTP下载文件的方法,包括了HTTP通信的创建、本地文件的写入等,非常具有实用价值,需要的朋友可以参考下...2020-06-25
- 这篇文章主要为大家详细介绍了SpringBoot实现excel文件生成和下载,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-02-09
- 本文章来人大家介绍一个php文件上传类的使用方法,期望此实例对各位php入门者会有不小帮助哦。 简介 Class.upload.php是用于管理上传文件的php文件上传类, 它可以帮...2016-11-25
- 又码了一个周末的代码,这次在做一些关于文件上传的东西。(PHP UPLOAD)小有收获项目是一个BT种子列表,用户有权限上传自己的种子,然后配合BT TRACK服务器把种子的信息写出来...2016-11-25
- 本文实例讲述了jQuery实现文件上传进度条效果的代码。分享给大家供大家参考。具体如下: 运行效果截图如下:具体代码如下:<!DOCTYPE html><html><head><meta charset="utf-8"><title>upload</title><link rel="stylesheet...2015-11-24
- 这篇文章主要介绍了详解springBoot启动时找不到或无法加载主类解决办法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-09-16
- 本篇文章主要说明的是与php文件上传的相关配置的知识点。PHP文件上传功能配置主要涉及php.ini配置文件中的upload_tmp_dir、upload_max_filesize、post_max_size等选项,下面一一说明。打开php.ini配置文件找到File Upl...2015-10-21
- 举一个案例:复制代码 代码如下:<?phpclass Downfile { function downserver($file_name){$file_path = "./img/".$file_name;//转码,文件名转为gb2312解决中文乱码$file_name = iconv("utf-8","gb2312",$file_name...2014-06-07
- EXCEL数据上传到SQL SERVER中的方法需要注意到三点!注意点一:要把EXCEL数据上传到SQL SERVER中必须提前把EXCEL传到服务器上.做法: 在ASP.NET环境中,添加一个FileUpload上传控件后台代码的E.X: 复制代码 代码如下: if...2013-09-23
- 这篇文章主要介绍了SpringBoot集成Redis实现消息队列的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-10
- 这篇文章主要介绍了解决Springboot get请求是参数过长的情况,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-09-17
- 这篇文章主要为大家详细介绍了js实现上传图片及时预览的相关资料,具有一定的参考价值,感兴趣的朋友可以参考一下...2016-05-09
- 这篇文章主要为大家详细介绍了Visual Studio 2015下载和安装图文教程,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-22
- DVWA (Dam Vulnerable Web Application)DVWA是用PHP+Mysql编写的一套用于常规WEB漏洞教学和检测的WEB脆弱性测试程序。包含了SQL注入、XSS、盲注等常见的一些安全漏洞...2016-11-25
Spring Boot项目@RestController使用重定向redirect方式
这篇文章主要介绍了Spring Boot项目@RestController使用重定向redirect方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-02- 这篇文章主要介绍了Springboot+TCP监听服务器搭建过程,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-10-28
- 这篇文章主要介绍了springBoot 项目排除数据库启动方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-10
- PHP代码如下:复制代码 代码如下:if (isset($_FILES["Filedata"]) || !is_uploaded_file($_FILES["Filedata"]["tmp_name"]) || $_FILES["Filedata"]["error"] != 0) { $upload_file = $_FILES['Filedata']; $fil...2013-10-04
- 本案例非通用,仅作笔记以备用 修改后的结果是 百度编辑器里上传的图片路径为/d/file/upload1...2014-07-03