背景:在springboot整合mongodb(一)基础上进行
从mongdb中取出文件
一、创建MyFile实体类
package com.zsx.entity;
import java.util.Arrays;
public class MyFile {
private byte[] file;
public MyFile() {
}
public MyFile(byte[] file) {
this.file = file;
}
public byte[] getFile() {
return file;
}
public void setFile(byte[] file) {
this.file = file;
}
@Override
public String toString() {
return "MyFile{" +
"file=" + Arrays.toString(file) +
'}';
}
}
二、FileController中添加api接口
@GetMapping("/image/{id}")
public ResponseEntity getFile(@PathVariable("id") String id) {
MyFile file = fileService.getMyFile(id);
if (file == null) {
return new ResponseEntity("fail", HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity(file, HttpStatus.OK);
}
三、FileService生成对应的方法
MyFile getMyFile(String id);
四、FileServiceImpl类中实现该方法
@Override
public MyFile getMyFile(String id) {
return new MyFile(fileDao.getById(id));
}
五、FileDao中进行数据处理
@Autowired
private GridFSBucket gridFSBucket;
public byte[] getById(String id) {
GridFSDownloadStream downloadStream = null;
try {
// 根据id查询文件
GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(id)));
// 打开流下载对象
downloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
return downloadStream.readAllBytes();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (downloadStream != null) {
downloadStream.close();
}
}
return null;
}
六、创建事务配置类TransactionalConfig
package com.zsx.config;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.MongoTransactionManager;
import org.springframework.data.mongodb.core.convert.MongoConverter;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
@Configuration
public class TransactionalConfig {
@Autowired
private MongoConverter mongoConverter;
@Bean
public GridFsTemplate gridFsTemplate(MongoDbFactory mongoDbFactory) {
return new GridFsTemplate(mongoDbFactory, mongoConverter);
}
@Bean
public MongoTransactionManager transactionManager(MongoDbFactory mongoDbFactory) {
return new MongoTransactionManager(mongoDbFactory);
}
@Bean
public GridFSBucket getGridFSBuckets(MongoDbFactory mongoDbFactory) {
MongoDatabase db = mongoDbFactory.getDb();
return GridFSBuckets.create(db);
}
}
七、启动引导类主程序
H:\JDK\jdk-11.0.3\bin\java.exe -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dspring.jmx.enabled=true -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true "-javaagent:H:\JetBrains\IntelliJ IDEA 2019.1.3\lib\idea_rt.jar=57705:H:\JetBrains\IntelliJ IDEA 2019.1.3\bin" -Dfile.encoding=UTF-8 -classpath F:\IdeaProjects\springbootmongodb\target\classes;E:\maven\repository\org\springframework\boot\spring-boot-starter-web\2.1.4.RELEASE\spring-boot-starter-web-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot-starter\2.1.4.RELEASE\spring-boot-starter-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot-starter-logging\2.1.4.RELEASE\spring-boot-starter-logging-2.1.4.RELEASE.jar;E:\maven\repository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;E:\maven\repository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;E:\maven\repository\org\apache\logging\log4j\log4j-to-slf4j\2.11.2\log4j-to-slf4j-2.11.2.jar;E:\maven\repository\org\apache\logging\log4j\log4j-api\2.11.2\log4j-api-2.11.2.jar;E:\maven\repository\org\slf4j\jul-to-slf4j\1.7.26\jul-to-slf4j-1.7.26.jar;E:\maven\repository\javax\annotation\javax.annotation-api\1.3.2\javax.annotation-api-1.3.2.jar;E:\maven\repository\org\yaml\snakeyaml\1.23\snakeyaml-1.23.jar;E:\maven\repository\org\springframework\boot\spring-boot-starter-json\2.1.4.RELEASE\spring-boot-starter-json-2.1.4.RELEASE.jar;E:\maven\repository\com\fasterxml\jackson\core\jackson-databind\2.9.8\jackson-databind-2.9.8.jar;E:\maven\repository\com\fasterxml\jackson\core\jackson-annotations\2.9.0\jackson-annotations-2.9.0.jar;E:\maven\repository\com\fasterxml\jackson\core\jackson-core\2.9.8\jackson-core-2.9.8.jar;E:\maven\repository\com\fasterxml\jackson\datatype\jackson-datatype-jdk8\2.9.8\jackson-datatype-jdk8-2.9.8.jar;E:\maven\repository\com\fasterxml\jackson\datatype\jackson-datatype-jsr310\2.9.8\jackson-datatype-jsr310-2.9.8.jar;E:\maven\repository\com\fasterxml\jackson\module\jackson-module-parameter-names\2.9.8\jackson-module-parameter-names-2.9.8.jar;E:\maven\repository\org\springframework\boot\spring-boot-starter-tomcat\2.1.4.RELEASE\spring-boot-starter-tomcat-2.1.4.RELEASE.jar;E:\maven\repository\org\apache\tomcat\embed\tomcat-embed-core\9.0.17\tomcat-embed-core-9.0.17.jar;E:\maven\repository\org\apache\tomcat\embed\tomcat-embed-el\9.0.17\tomcat-embed-el-9.0.17.jar;E:\maven\repository\org\apache\tomcat\embed\tomcat-embed-websocket\9.0.17\tomcat-embed-websocket-9.0.17.jar;E:\maven\repository\org\hibernate\validator\hibernate-validator\6.0.16.Final\hibernate-validator-6.0.16.Final.jar;E:\maven\repository\javax\validation\validation-api\2.0.1.Final\validation-api-2.0.1.Final.jar;E:\maven\repository\org\jboss\logging\jboss-logging\3.3.2.Final\jboss-logging-3.3.2.Final.jar;E:\maven\repository\com\fasterxml\classmate\1.4.0\classmate-1.4.0.jar;E:\maven\repository\org\springframework\spring-web\5.1.6.RELEASE\spring-web-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-beans\5.1.6.RELEASE\spring-beans-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-webmvc\5.1.6.RELEASE\spring-webmvc-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-aop\5.1.6.RELEASE\spring-aop-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-context\5.1.6.RELEASE\spring-context-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-expression\5.1.6.RELEASE\spring-expression-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot-starter-data-mongodb\2.1.4.RELEASE\spring-boot-starter-data-mongodb-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\data\spring-data-mongodb\2.1.6.RELEASE\spring-data-mongodb-2.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-tx\5.1.6.RELEASE\spring-tx-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\data\spring-data-commons\2.1.6.RELEASE\spring-data-commons-2.1.6.RELEASE.jar;E:\maven\repository\org\slf4j\slf4j-api\1.7.26\slf4j-api-1.7.26.jar;E:\maven\repository\org\springframework\spring-core\5.1.6.RELEASE\spring-core-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-jcl\5.1.6.RELEASE\spring-jcl-5.1.6.RELEASE.jar;E:\maven\repository\org\mongodb\mongodb-driver\3.8.2\mongodb-driver-3.8.2.jar;E:\maven\repository\org\mongodb\bson\3.8.2\bson-3.8.2.jar;E:\maven\repository\org\mongodb\mongodb-driver-core\3.8.2\mongodb-driver-core-3.8.2.jar;E:\maven\repository\org\springframework\boot\spring-boot-configuration-processor\2.1.4.RELEASE\spring-boot-configuration-processor-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot-devtools\2.1.4.RELEASE\spring-boot-devtools-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot\2.1.4.RELEASE\spring-boot-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot-autoconfigure\2.1.4.RELEASE\spring-boot-autoconfigure-2.1.4.RELEASE.jar com.zsx.MongoDBApplication
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.4.RELEASE)
2019-07-08 21:56:43.290 INFO 7576 --- [ restartedMain] com.zsx.MongoDBApplication : Starting MongoDBApplication on zsx with PID 7576 (F:\IdeaProjects\springbootmongodb\target\classes started by admin in F:\IdeaProjects\springbootmongodb)
2019-07-08 21:56:43.293 INFO 7576 --- [ restartedMain] com.zsx.MongoDBApplication : No active profile set, falling back to default profiles: default
2019-07-08 21:56:43.515 INFO 7576 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2019-07-08 21:56:43.517 INFO 7576 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2019-07-08 21:56:44.727 INFO 7576 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-07-08 21:56:44.809 INFO 7576 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 78ms. Found 1 repository interfaces.
2019-07-08 21:56:45.257 INFO 7576 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$c3a4430d] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-07-08 21:56:45.739 INFO 7576 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2019-07-08 21:56:45.769 INFO 7576 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-07-08 21:56:45.769 INFO 7576 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.17]
2019-07-08 21:56:45.788 INFO 7576 --- [ restartedMain] o.a.catalina.core.AprLifecycleListener : An older version [1.2.16] of the APR based Apache Tomcat Native library is installed, while Tomcat recommends a minimum version of [1.2.21]
2019-07-08 21:56:45.789 INFO 7576 --- [ restartedMain] o.a.catalina.core.AprLifecycleListener : Loaded APR based Apache Tomcat Native library [1.2.16] using APR version [1.6.3].
2019-07-08 21:56:45.789 INFO 7576 --- [ restartedMain] o.a.catalina.core.AprLifecycleListener : APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
2019-07-08 21:56:45.789 INFO 7576 --- [ restartedMain] o.a.catalina.core.AprLifecycleListener : APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true]
2019-07-08 21:56:46.874 INFO 7576 --- [ restartedMain] o.a.catalina.core.AprLifecycleListener : OpenSSL successfully initialized [OpenSSL 1.0.2m 2 Nov 2017]
2019-07-08 21:56:47.049 INFO 7576 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-07-08 21:56:47.049 INFO 7576 --- [ restartedMain] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3531 ms
2019-07-08 21:56:47.643 INFO 7576 --- [ restartedMain] org.mongodb.driver.cluster : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2019-07-08 21:56:47.715 INFO 7576 --- [localhost:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:1, serverValue:184}] to localhost:27017
2019-07-08 21:56:47.725 INFO 7576 --- [localhost:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 0, 10]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=7966222}
2019-07-08 21:56:47.916 INFO 7576 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2019-07-08 21:56:48.472 INFO 7576 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-07-08 21:56:48.693 INFO 7576 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2019-07-08 21:56:48.698 INFO 7576 --- [ restartedMain] com.zsx.MongoDBApplication : Started MongoDBApplication in 6.396 seconds (JVM running for 8.459)
八、打开数据库(此处以图片为例)
九、打开postman
查看请求http://localhost:8080/api/v1/file/5d234d4efbfab724c88de9da
十、查看
复制生成的字节数组内容,用在线工具将其还原成图片
从以上结果看出,获取图片文件成功