浏览代码

修改GridFsUtil

Airhead 8 年之前
父节点
当前提交
b109f27c55

+ 1 - 3
hos-broker/src/main/java/com/yihu/hos/broker/HosBrokerApplication.java

@ -4,13 +4,11 @@ import com.yihu.hos.broker.services.camel.CamelStartBoot;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
@SpringBootApplication
@EnableScheduling
public class HosBrokerApplication extends SpringBootServletInitializer implements CommandLineRunner {

+ 3 - 0
hos-broker/src/main/resources/application.yml

@ -42,6 +42,7 @@ spring:
      password: esb
      authenticationDatabase: admin
      database: log
      gridFsDatabase: upload
  gateway:
    ip: localhost
    port: 8066
@ -84,6 +85,7 @@ spring:
      password: esb
      authenticationDatabase: admin
      database: log
      gridFsDatabase: upload
  gateway:
    ip: localhost
    port: 8066
@ -124,6 +126,7 @@ spring:
      password: esb
      authenticationDatabase: admin
      database: log
      gridFsDatabase: upload
  gateway:
    ip: localhost
    port: 8066

+ 5 - 2
hos-rest/hos-rest.iml

@ -178,8 +178,6 @@
    <orderEntry type="library" name="Maven: io.springfox:springfox-spring-web:2.4.0" level="project" />
    <orderEntry type="library" name="Maven: io.springfox:springfox-swagger-ui:2.4.0" level="project" />
    <orderEntry type="library" name="Maven: javax.transaction:javax.transaction-api:1.2" level="project" />
    <orderEntry type="library" name="Maven: com.yihu.core:ehr-dbhelper:1.1.9" level="project" />
    <orderEntry type="library" name="Maven: com.yihu.core:html2image:0.9" level="project" />
    <orderEntry type="library" name="Maven: org.springframework:spring-orm:4.3.3.RELEASE" level="project" />
    <orderEntry type="library" name="Maven: org.springframework:spring-jdbc:4.3.3.RELEASE" level="project" />
    <orderEntry type="library" name="Maven: com.yihu.core:api-dict:1.6.0" level="project" />
@ -196,6 +194,8 @@
    <orderEntry type="library" name="Maven: org.javassist:javassist:3.20.0-GA" level="project" />
    <orderEntry type="library" name="Maven: antlr:antlr:2.7.7" level="project" />
    <orderEntry type="library" name="Maven: org.jboss:jandex:1.1.0.Final" level="project" />
    <orderEntry type="library" name="Maven: com.yihu.core:ehr-dbhelper:1.1.9" level="project" />
    <orderEntry type="library" name="Maven: com.yihu.core:html2image:0.9" level="project" />
    <orderEntry type="library" name="Maven: org.apache.camel:camel-core:2.18.0" level="project" />
    <orderEntry type="library" name="Maven: com.sun.xml.bind:jaxb-core:2.2.11" level="project" />
    <orderEntry type="library" name="Maven: com.sun.xml.bind:jaxb-impl:2.2.11" level="project" />
@ -257,6 +257,9 @@
    <orderEntry type="library" name="Maven: org.eclipse.jetty:jetty-client:9.3.11.v20160721" level="project" />
    <orderEntry type="library" name="Maven: org.eclipse.jetty:jetty-jmx:9.3.11.v20160721" level="project" />
    <orderEntry type="library" name="Maven: org.apache.camel:camel-jetty-common:2.18.0" level="project" />
    <orderEntry type="library" name="Maven: org.apache.camel:camel-mongodb:2.18.0" level="project" />
    <orderEntry type="library" name="Maven: org.apache.camel:camel-jackson:2.18.0" level="project" />
    <orderEntry type="library" name="Maven: com.fasterxml.jackson.module:jackson-module-jaxb-annotations:2.8.3" level="project" />
    <orderEntry type="library" name="Maven: xom:xom:1.2.5" level="project" />
    <orderEntry type="library" name="Maven: xerces:xercesImpl:2.8.0" level="project" />
    <orderEntry type="library" name="Maven: xalan:xalan:2.7.0" level="project" />

+ 105 - 95
hos-rest/pom.xml

@ -1,107 +1,117 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
	<groupId>com.yihu.hos</groupId>
	<artifactId>hos-rest</artifactId>
	<version>1.1.1-SNAPSHOT</version>
	<packaging>jar</packaging>
    <groupId>com.yihu.hos</groupId>
    <artifactId>hos-rest</artifactId>
    <version>1.1.1-SNAPSHOT</version>
    <packaging>jar</packaging>
	<name>hos-rest</name>
	<description>ESB业务服务模块,实现ESB基础业务逻辑</description>
    <name>hos-rest</name>
    <description>ESB业务服务模块,实现ESB基础业务逻辑</description>
	<parent>
		<groupId>com.yihu.hos</groupId>
		<artifactId>hos-web-camel-dependencies</artifactId>
		<version>1.1.1-SNAPSHOT</version>
		<relativePath>../hos-web-camel-dependencies</relativePath><!-- lookup parent from repository -->
	</parent>
    <parent>
        <groupId>com.yihu.hos</groupId>
        <artifactId>hos-web-camel-dependencies</artifactId>
        <version>1.1.1-SNAPSHOT</version>
        <relativePath>../hos-web-camel-dependencies</relativePath><!-- lookup parent from repository -->
    </parent>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
	<!--用于发布到服务器 对应setting的对应server表情里面的id -->
	<distributionManagement>
		<repository>
			<id>Releases</id>
			<name>Releases</name>
			<url>http://172.19.103.47:8081/nexus/content/repositories/releases/</url>
		</repository>
		<snapshotRepository>
			<id>snapshots</id>
			<name>Snapshots</name>
			<url>http://172.19.103.47:8081/nexus/content/repositories/snapshots/</url>
		</snapshotRepository>
	</distributionManagement>
	<repositories>
		<repository>
			<id>repositoryCentral</id>
			<name>repositoryCentral</name>
			<url>http://172.19.103.47:8081/nexus/content/repositories/central/</url>
		</repository>
		<repository>
			<id>repositoryReleases</id>
			<name>repositoryReleases</name>
			<url>http://172.19.103.47:8081/nexus/content/repositories/releases/</url>
		</repository>
	</repositories>
    <!--用于发布到服务器 对应setting的对应server表情里面的id -->
    <distributionManagement>
        <repository>
            <id>Releases</id>
            <name>Releases</name>
            <url>http://172.19.103.47:8081/nexus/content/repositories/releases/</url>
        </repository>
        <snapshotRepository>
            <id>snapshots</id>
            <name>Snapshots</name>
            <url>http://172.19.103.47:8081/nexus/content/repositories/snapshots/</url>
        </snapshotRepository>
    </distributionManagement>
    <repositories>
        <repository>
            <id>repositoryCentral</id>
            <name>repositoryCentral</name>
            <url>http://172.19.103.47:8081/nexus/content/repositories/central/</url>
        </repository>
        <repository>
            <id>repositoryReleases</id>
            <name>repositoryReleases</name>
            <url>http://172.19.103.47:8081/nexus/content/repositories/releases/</url>
        </repository>
    </repositories>
	<dependencies>
		<dependency>
			<groupId>com.yihu.hos</groupId>
			<artifactId>hos-web-framework</artifactId>
			<version>1.1.1-SNAPSHOT</version>
			<exclusions>
				<exclusion>
					<groupId>org.springframework.boot</groupId>
					<artifactId>spring-boot-starter-data-jpa</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>com.yihu.core</groupId>
			<artifactId>api-dict</artifactId>
			<version>1.6.0</version>
		</dependency>
		<dependency>
			<groupId>com.yihu.core</groupId>
			<artifactId>core-rpc</artifactId>
			<version>2.2.0</version>
		</dependency>
		<dependency>
			<groupId>com.yihu.core</groupId>
			<artifactId>api-config</artifactId>
			<version>2.2.0</version>
		</dependency>
		<dependency>
			<groupId>com.yihu.core</groupId>
			<artifactId>core-db</artifactId>
			<version>1.3.0</version>
		</dependency>
    <dependencies>
        <dependency>
            <groupId>com.yihu.hos</groupId>
            <artifactId>hos-web-framework</artifactId>
            <version>1.1.1-SNAPSHOT</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-data-jpa</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.core</groupId>
            <artifactId>api-dict</artifactId>
            <version>1.6.0</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.core</groupId>
            <artifactId>core-rpc</artifactId>
            <version>2.2.0</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.core</groupId>
            <artifactId>api-config</artifactId>
            <version>2.2.0</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.core</groupId>
            <artifactId>core-db</artifactId>
            <version>1.3.0</version>
        </dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>4.3.11.Final</version>
		</dependency>
	</dependencies>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.11.Final</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.core</groupId>
            <artifactId>ehr-dbhelper</artifactId>
            <version>1.1.9</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.core</groupId>
            <artifactId>html2image</artifactId>
            <version>0.9</version>
        </dependency>
    </dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

+ 6 - 0
hos-web-camel-dependencies/pom.xml

@ -110,6 +110,12 @@
            <artifactId>camel-jetty</artifactId>
            <version>${camel.version}</version> <!-- use the same version as your Camel core version -->
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-mongodb</artifactId>
            <version>${camel.version}</version>
            <!-- use the same version as your Camel core version -->
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.activemq/activemq-camel -->
        <dependency>
            <groupId>xom</groupId>

+ 0 - 11
hos-web-framework-dependencies/pom.xml

@ -134,17 +134,6 @@
            <artifactId>javax.transaction-api</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.core</groupId>
            <artifactId>ehr-dbhelper</artifactId>
            <version>1.1.9</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.core</groupId>
            <artifactId>html2image</artifactId>
            <version>0.9</version>
        </dependency>
    </dependencies>
    <build>

+ 95 - 264
hos-web-framework/src/main/java/com/yihu/hos/web/framework/util/GridFSUtil.java

@ -1,31 +1,23 @@
package com.yihu.hos.web.framework.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.BasicDBObject;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import com.mongodb.client.gridfs.GridFSFindIterable;
import com.mongodb.client.gridfs.GridFSUploadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.mongodb.client.gridfs.model.GridFSUploadOptions;
import com.mongodb.client.model.Filters;
import com.yihu.ehr.dbhelper.mongodb.MongodbFactory;
import com.yihu.ehr.dbhelper.mongodb.MongodbHelper;
import com.mongodb.gridfs.GridFSDBFile;
import com.yihu.hos.core.file.FileUtil;
import eu.medsea.mimeutil.MimeUtil;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsCriteria;
import org.springframework.data.mongodb.gridfs.GridFsOperations;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.*;
import java.sql.Blob;
import java.util.*;
@ -40,14 +32,11 @@ public class GridFSUtil {
    public static final int defaultChunkSize = 1024 * 1024 * 4;
    @Autowired
    private static GridFsOperations gridFsOperations;
    public static ObjectId uploadFile(String dbName, Blob blob, String fileType, Map<String, Object> params) {
        //获取mongodb连接
//        MongodbHelper mongoOrigin = new MongodbHelper(dbName);
        //创建一个容器
        MongoDatabase db = MongodbFactory.getDB(dbName);
        GridFSBucket gridFS = GridFSBuckets.create(db);
        String fileName = UUID.randomUUID().toString() + "." + fileType;
//        String fileName = UUID.randomUUID().toString() + "." + fileType;
        //自定义字段
        Document metaDocument = new Document();
        if (params != null && params.size() > 0) {
@ -59,21 +48,14 @@ public class GridFSUtil {
        // Create some custom options
        GridFSUploadOptions gridFSUploadOptions = new GridFSUploadOptions()
                .chunkSizeBytes(defaultChunkSize).metadata(metaDocument);
        GridFSUploadStream uploadStream = gridFS.openUploadStream(fileName, gridFSUploadOptions);
        try {
            byte[] data = FileUtil.toByteArray(blob.getBinaryStream());
            uploadStream.write(data);
            ObjectId id = uploadStream.getFileId();
            if (id != null) {
                return id;
            com.mongodb.gridfs.GridFSFile gridFSFile = gridFsOperations.store(blob.getBinaryStream(), gridFSUploadOptions);
            if (gridFSFile != null) {
                return (ObjectId) gridFSFile.getId();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (uploadStream != null) {
                uploadStream.close();
            }
        }
        return null;
    }
@ -86,13 +68,6 @@ public class GridFSUtil {
     * @param params   自定义保存字段
     */
    public static boolean uploadFile(String dbName, String filePath, Map<String, Object> params) {
        //获取mongodb连接
//        MongodbHelper mongoOrigin = new MongodbHelper(dbName);
        //创建一个容器
        MongoDatabase db = MongodbFactory.getDB(dbName);
        GridFSBucket gridFS = GridFSBuckets.create(db);
        File readFile = new File(filePath);
        //自定义字段
        Document metaDocument = new Document();
        if (params != null && params.size() > 0) {
@ -104,20 +79,23 @@ public class GridFSUtil {
        // Create some custom options
        GridFSUploadOptions gridFSUploadOptions = new GridFSUploadOptions()
                .chunkSizeBytes(defaultChunkSize).metadata(metaDocument);
        GridFSUploadStream uploadStream = gridFS.openUploadStream(readFile.getName(), gridFSUploadOptions);
        FileInputStream fileInputStream = null;
        try {
            byte[] data = FileUtil.toByteArray(filePath);
            uploadStream.write(data);
            ObjectId id = uploadStream.getFileId();
            if (id != null) {
            File readFile = new File(filePath);
            fileInputStream = new FileInputStream(readFile);
            com.mongodb.gridfs.GridFSFile gridFSFile = gridFsOperations.store(fileInputStream, gridFSUploadOptions);
            if (gridFSFile != null) {
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (uploadStream != null) {
                uploadStream.close();
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
@ -128,30 +106,24 @@ public class GridFSUtil {
     *
     * @param dbName   数据库名
     * @param savePath 文件保存路径
     * @param objId    GridFS文件保存ObjectId
     * @param objectId GridFS文件保存ObjectId
     * @return
     */
    public static String downFile(String dbName, String savePath, ObjectId objId) {
        //穿件mongodb连接
//        MongodbHelper mongoOrigin = new MongodbHelper(dbName);
        //创建一个容器
        MongoDatabase db = MongodbFactory.getDB(dbName);
        GridFSBucket gridFS = GridFSBuckets.create(db);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        gridFS.downloadToStream(objId, out);
    public static String downFile(String dbName, String savePath, ObjectId objectId) {
        FileOutputStream fileOutputStream = null;
        try {
            boolean succ = FileUtil.writeFile(savePath, out.toByteArray(), "utf-8");
            if (succ) {
                return savePath;
            } else {
                return null;
            }
            GridFSDBFile gridFSDBFile = gridFsOperations.findOne(Query.query(GridFsCriteria.where("_id").is(objectId)));
            fileOutputStream = new FileOutputStream(savePath);
            gridFSDBFile.writeTo(fileOutputStream);
            return savePath;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
            if (fileOutputStream != null) {
                try {
                    out.close();
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
@ -171,28 +143,23 @@ public class GridFSUtil {
    public static Map<String, StringBuffer> downFileList(String dbName, String savePath, List<GridFSFile> fsFiles) {
        StringBuffer stringBuffer = new StringBuffer();
        Map<String, String> fileNames = new HashMap<>();
        //穿件mongodb连接
//        MongodbHelper mongoOrigin = new MongodbHelper(dbName);
        //创建一个容器
        MongoDatabase db = MongodbFactory.getDB(dbName);
        GridFSBucket gridFS = GridFSBuckets.create(db);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        if (fsFiles != null && fsFiles.size() > 0) {
            for (GridFSFile fsFile : fsFiles) {
                ObjectId objId = fsFile.getObjectId();
                ObjectId objectId = fsFile.getObjectId();
                String fileType = fsFile.getFilename().substring(fsFile.getFilename().lastIndexOf("."));
                String newName = UUID.randomUUID().toString() + "." + fileType;
                gridFS.downloadToStream(objId, out);
                GridFSDBFile gridFSDBFile = gridFsOperations.findOne(Query.query(GridFsCriteria.where("_id").is(objectId)));
                try {
                    boolean succ = FileUtil.writeFile(savePath + "/" + newName, out.toByteArray(), "utf-8");
                    if (succ) {
                        String type = getMimeType(out.toByteArray());
                        fileNames.put(newName, type);
//                        stringBuffer.append(newName).append(",");
                        continue;
                    } else {
                    gridFSDBFile.writeTo(out);
                    boolean success = FileUtil.writeFile(savePath + "/" + newName, out.toByteArray(), "utf-8");
                    if (!success) {
                        break;
                    }
                    String type = getMimeType(out.toByteArray());
                    fileNames.put(newName, type);
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
@ -215,29 +182,24 @@ public class GridFSUtil {
    public static Map<String, StringBuffer> downFilesByObjectIds(String dbName, String savePath, List<ObjectId> ids) {
        StringBuffer stringBuffer = new StringBuffer();
        Map<String, String> fileNames = new HashMap<>();
        //穿件mongodb连接
//        MongodbHelper mongoOrigin = new MongodbHelper(dbName);
        //创建一个容器
        MongoDatabase db = MongodbFactory.getDB(dbName);
        GridFSBucket gridFS = GridFSBuckets.create(db);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        List<GridFSFile> fsFiles = findFsFiles(dbName, ids);
        List<GridFSDBFile> fsFiles = findFsFiles(dbName, ids);
        if (fsFiles != null && fsFiles.size() > 0) {
            for (GridFSFile fsFile : fsFiles) {
                ObjectId objId = fsFile.getObjectId();
            for (GridFSDBFile fsFile : fsFiles) {
                ObjectId objectId = (ObjectId) fsFile.getId();
                String fileType = fsFile.getFilename().substring(fsFile.getFilename().lastIndexOf("."));
                String newName = UUID.randomUUID().toString() + "." + fileType;
                gridFS.downloadToStream(objId, out);
                GridFSDBFile gridFSDBFile = gridFsOperations.findOne(Query.query(GridFsCriteria.where("_id").is(objectId)));
                try {
                    boolean succ = FileUtil.writeFile(savePath + "/" + newName, out.toByteArray(), "utf-8");
                    if (succ) {
                        String type = getMimeType(out.toByteArray());
                        fileNames.put(newName, type);
//                        stringBuffer.append(newName).append(",");
                        continue;
                    } else {
                    gridFSDBFile.writeTo(out);
                    boolean success = FileUtil.writeFile(savePath + "/" + newName, out.toByteArray(), "utf-8");
                    if (!success) {
                        break;
                    }
                    String type = getMimeType(out.toByteArray());
                    fileNames.put(newName, type);
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
@ -261,13 +223,10 @@ public class GridFSUtil {
     * 删除 mongodb-GridFS文件
     *
     * @param dbName
     * @param objId
     * @param objectId
     */
    public static void deleteFile(String dbName, ObjectId objId) {
//        MongodbHelper mongoOrigin = new MongodbHelper(dbName);
        MongoDatabase db = MongodbFactory.getDB(dbName);
        GridFSBucket gridFS = GridFSBuckets.create(db);
        gridFS.delete(objId);
    public static void deleteFile(String dbName, ObjectId objectId) {
        gridFsOperations.delete(Query.query(GridFsCriteria.where("_id").is(objectId)));
    }
    /**
@ -277,29 +236,13 @@ public class GridFSUtil {
     * @param filters 查询条件
     * @return files集合
     */
    public static List<GridFSFile> findFiles(String dbName, Map<String, Object> filters) {
        //穿件mongodb连接
        List<GridFSFile> list = new ArrayList<>();
        //创建一个容器
        MongoDatabase db = MongodbFactory.getDB(dbName);
        GridFSBucket gridFSBucket = GridFSBuckets.create(db);
        List<Bson> querys = new ArrayList<>();
        //添加查询条件
        if (filters != null && filters.size() > 0) {
            for (Map.Entry<String, Object> entry : filters.entrySet()) {
                String key = entry.getKey();
                querys.add(Filters.eq(key, entry.getValue()));
            }
    public static List<GridFSDBFile> findFiles(String dbName, Map<String, Object> filters) {
        Query query = new Query();
        if (filters != null) {
            filters.forEach((key, value) -> query.addCriteria(GridFsCriteria.where(key).is(value)));
        }
//        GridFSFindIterable gsIterable=gridFSBucket.find(Filters.eq("metadata.cda_id", "111"));
        GridFSFindIterable gsIterable = gridFSBucket.find(Filters.and(querys));
        MongoCursor<GridFSFile> it = gsIterable.iterator();
        while (it.hasNext()) {
            GridFSFile fsFile = it.next();
            list.add(fsFile);
        }
        return list;
        return gridFsOperations.find(query);
    }
    /**
@ -309,116 +252,16 @@ public class GridFSUtil {
     * @param ids    objectId集合
     * @return
     */
    public static List<GridFSFile> findFsFiles(String dbName, List<ObjectId> ids) {
        //穿件mongodb连接
        List<GridFSFile> list = new ArrayList<>();
        //创建一个容器
        MongoDatabase db = MongodbFactory.getDB(dbName);
        GridFSBucket gridFSBucket = GridFSBuckets.create(db);
        List<Bson> querys = new ArrayList<>();
        //添加查询条件
        if (ids != null && ids.size() > 0) {
            querys.add(Filters.in("_id", ids));
        }
        GridFSFindIterable gsIterable = null;
        if (querys.size() > 0) {
            gsIterable = gridFSBucket.find(Filters.and(querys));
        } else {
            gsIterable = gridFSBucket.find();
        }
    public static List<GridFSDBFile> findFsFiles(String dbName, List<ObjectId> ids) {
        List<GridFSDBFile> list = new ArrayList<>();
        ids.forEach(objectId -> {
            GridFSDBFile gridFSDBFile = gridFsOperations.findOne(Query.query(GridFsCriteria.where("_id").is(objectId)));
            list.add(gridFSDBFile);
        });
        MongoCursor<GridFSFile> it = gsIterable.iterator();
        while (it.hasNext()) {
            GridFSFile fsFile = it.next();
            list.add(fsFile);
        }
        return list;
    }
    public static Map parseJsonToMap(JSONObject condition) {
        ObjectMapper objectMapper = new ObjectMapper();
        HashMap map = new HashMap();
        try {
            Iterator fileNames = (Iterator) condition.names();
            while (fileNames.hasNext()) {
                String fieldName = (String) fileNames.next();
                Object valueNode = condition.get(fieldName);
                if (valueNode instanceof Blob) {
                    map.put(fieldName, valueNode);
                } else {
                    map.put(fieldName, condition.get(fieldName).toString());
                }
            }
        } catch (Exception var7) {
            var7.printStackTrace();
        }
        return map;
    }
    //TODO  测试所用,后删除
    public static void tTestFind(String tableName, String collection, Map<String, Object> params) {
        MongodbHelper mongodbHelper = new MongodbHelper(tableName);
        BasicDBObject basicDBObject = new BasicDBObject();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            String key = entry.getKey();
            basicDBObject.append(key, entry.getValue());
        }
        FindIterable<Document> documents = mongodbHelper.query(collection, basicDBObject, null, null);
        MongoCursor<Document> it = documents.iterator();
        while (it.hasNext()) {
            Document document = it.next();
            List<Document> fileList = (List<Document>) document.get("files");
            Document jsonNode = fileList.get(0);
            List files = (List) jsonNode.get("files_id");
            List<GridFSFile> fs = findFsFiles("mydb", files);
            System.out.println(files.toString());
            String filePath = "e:/test/";
            Map<String, StringBuffer> path = downFileList("mydb", filePath, fs);
        }
    }
//    public static void main(String[] args) {
//        try {
//            //上传
//            Map<String,Object> params= new HashMap<>();
////            params.put("cda_id","111");
////            params.put("report_id","1001");
//            params.put("patient_id","1001");
//            params.put("event_no","1001");
////            String fileName = "e:/test/肺2.jpg";
////            uploadFile("mydb", fileName,params);
//            //下载
////            String filePath="e:/test/xiao_copy.jpg";
////            downFile("mydb",filePath,"579067939724e11514b2eead");
//            //删除
////            deleteFile("mydb","57906e369724e11dd8e75798");
//            //查询
////            List<GridFSFile> fsFiles  = findFiles("mydb",params);
//            // 根据objectId集合 查询
////            List<ObjectId> list=new ArrayList<>();
////            list.add(new ObjectId("5791c9399724e12b9437b229"));
////            list.add(new ObjectId("5795aab07a2b9020ec19fdfa"));
//
////            List<GridFSFile> fs=findFsFiles("mydb",list);
//            //测试查询类
//            tTestFind("document","CDA_TEST",params);
//            //批量下载
////            String filePath="e:/test/";
////            downFileList("mydb",filePath, fs);
//
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
    /*************************************** MineType 工具类 *********************************/
    /**
@ -499,31 +342,28 @@ public class GridFSUtil {
     * @param filePath 文件路径
     */
    public static String uploadFile(String dbName, String filePath, String fileName) {
        //获取mongodb连接
//        MongodbHelper mongoOrigin = new MongodbHelper(dbName);
        //创建一个容器
        MongoDatabase db = MongodbFactory.getDB(dbName);
        GridFSBucket gridFS = GridFSBuckets.create(db);
        //自定义字段
        Document metaDocument = new Document();
        // Create some custom options
        GridFSUploadOptions gridFSUploadOptions = new GridFSUploadOptions()
                .chunkSizeBytes(defaultChunkSize).metadata(metaDocument);
        GridFSUploadStream uploadStream = gridFS.openUploadStream(fileName, gridFSUploadOptions);
        FileInputStream fileInputStream = null;
        try {
            byte[] data = FileUtil.toByteArray(filePath);
            uploadStream.write(data);
            ObjectId id = uploadStream.getFileId();
            fileInputStream = new FileInputStream(filePath);
            com.mongodb.gridfs.GridFSFile gridFSFile = gridFsOperations.store(fileInputStream, gridFSUploadOptions);
            ObjectId id = (ObjectId) gridFSFile.getId();
            if (id != null) {
                return fileName;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (uploadStream != null) {
                uploadStream.close();
                File file = new File(filePath);
                file.deleteOnExit();
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
@ -549,19 +389,17 @@ public class GridFSUtil {
    /**
     * 读取文件内容
     * @param dbName    数据库名
     * @param fileName  文件名
     *
     * @param dbName   数据库名
     * @param fileName 文件名
     * @return
     */
    public static String readFile(String dbName, String fileName){
    public static String readFile(String dbName, String fileName) {
        try {
            MongoDatabase db = MongodbFactory.getDB(dbName);
            GridFSBucket gridFS = GridFSBuckets.create(db);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            gridFS.downloadToStreamByName(fileName, out);
            String content = FileUtil.readFileText(out.toByteArray());
            out.close();
            return content;
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            GridFSDBFile gridFSDBFile = gridFsOperations.findOne(Query.query(GridFsCriteria.where("").is(fileName)));
            gridFSDBFile.writeTo(byteArrayOutputStream);
            return byteArrayOutputStream.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
@ -578,26 +416,19 @@ public class GridFSUtil {
     * @return
     */
    public static String downFile(String dbName, String savePath, String fileName) {
        //穿件mongodb连接
//        MongodbHelper mongoOrigin = new MongodbHelper(dbName);
        //创建一个容器
        MongoDatabase db = MongodbFactory.getDB(dbName);
        GridFSBucket gridFS = GridFSBuckets.create(db);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        gridFS.downloadToStreamByName(fileName, out);
        FileOutputStream fileOutputStream = null;
        try {
            boolean succ = FileUtil.writeFile(savePath, out.toByteArray(), "UTF-8");
            if (succ) {
                return savePath;
            } else {
                return null;
            }
            File file = new File(savePath);
            fileOutputStream = new FileOutputStream(file);
            GridFSDBFile gridFSDBFile = gridFsOperations.findOne(Query.query(GridFsCriteria.where("").is(fileName)));
            gridFSDBFile.writeTo(fileOutputStream);
            return savePath;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
            if (fileOutputStream != null) {
                try {
                    out.close();
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

+ 10 - 1
pom.xml

@ -133,7 +133,16 @@
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.9</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.core</groupId>
            <artifactId>ehr-dbhelper</artifactId>
            <version>1.1.9</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.core</groupId>
            <artifactId>html2image</artifactId>
            <version>0.9</version>
        </dependency>
    </dependencies>