1. 程式人生 > >java連線mongdb3操作檔案

java連線mongdb3操作檔案

引入pom依賴

 <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver</artifactId>
            <version>3.3.0</version>
 </dependency>

如果不用依賴則引入jar

bson-3.3.0.jar

mongodb-driver-core-3.3.0.jar

mongo-java-driver-3.2.2.jar

morphia-1.1.0.jar

Java工具類

import com.mongodb.MongoClient;
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.model.GridFSUploadOptions;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @version 1.0
 * @description
 * @modified
 */
public class MongoDbFSUtil {
    private static Logger log = LoggerFactory.getLogger(MongoDbFSUtil.class);

    //讀取配置檔案
    private  final static Properties properties = new Properties();
    static {
        try {
            URL url = MongoDbFSUtil.class.getClassLoader().getResource("application.properties");
            if (url != null) {
                log.info("application.properties已載入");
                InputStream in = url.openStream();
                try {
                    properties.load(in);
                } finally {
                    in.close();
                }
            }
        } catch (IOException e) {
            log.info("載入application.properties失敗" + e);
        }
    }

    //mongdb配置引數spring不能載入靜態配置故用此方法
    private static class Config {

        public static String host = null;
        public static String port = null;
        public static String database = null;
        public static String temporaryFile_dir = null;

        static {
            host = properties.getProperty("spring.data.mongodb.host");
            port = properties.getProperty("spring.data.mongodb.port");
            database =properties.getProperty("spring.data.mongodb.database");
            temporaryFile_dir =properties.getProperty("temporaryFile_dir");
        }
    }

    //連線mongdb
    private static final class MongoInstance {
        public final static MongoClient client;

        static {
            client = new MongoClient(Config.host, Integer.parseInt(Config.port));
        }
    }

    //連線資料庫
    public static MongoDatabase getDatabase() {
        return MongoInstance.client.getDatabase(Config.database);
    }

    /**
     * 上傳檔案
     * @param fileName
     * @return returnId
     */
    public static String uploadFileToGridFS(String fileName) {
        String pathname=Config.temporaryFile_dir+fileName;
        File file = new File(pathname);
        InputStream in = null;
        String returnId = null;
        String pathName = file.getPath();
        String[] pathNameArray = pathName.split("\\\\");
        String[] name = pathNameArray[pathNameArray.length-1].split("\\.");
        String filename = name[0];
        String type = name[name.length-1];
        try {
            in = new FileInputStream(file);
            GridFSBucket bucket = GridFSBuckets.create(getDatabase());
            GridFSUploadOptions options = new GridFSUploadOptions();
            //設定除filename以外的其他資訊
            Document metadata = new Document();
            metadata.append("contentType", type);
            options.metadata(metadata);
            ObjectId fileId = bucket.uploadFromStream(filename+type, in);
            returnId = fileId.toHexString();
            log.info("mongdb檔案上傳成功"+returnId);
        } catch (IOException e) {
            log.info("upload fail:" + e);
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                log.info("close inputstream fail:" + e);
            }
            //刪除臨時檔案
            CreatePdf cpdf= new CreatePdf();
            cpdf.deleteFile(pathname);
            log.info("檔案刪除成功");
        }
        return returnId;
    }

    /**
     * 通過objectid和file下載檔案
     * @param objectId
     * @param file
     */
    public static void downloadFile(String objectId, File file) {
        OutputStream os = null;
        try {
            os = new FileOutputStream(file);
            GridFSBucket bucket = GridFSBuckets.create(getDatabase());
            bucket.downloadToStream(new ObjectId(objectId), os);
            log.info("檔案下載成功");
        } catch (IOException e) {
            log.info("download fail:" + e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    log.info("close outputstream fail:" + e);
                }
            }
        }
    }


    /**
     * 通過objectid查詢並輸出到前端
     * @param objectId
     */
    public static void downloadFile2(String objectId, HttpServletResponse response) {
        OutputStream sos = null;
        try {
            GridFSBucket bucket = GridFSBuckets.create(getDatabase());
            sos = response.getOutputStream();
            //獲取輸出流
            bucket.downloadToStream(new ObjectId(objectId), sos);
            log.info("檔案下載成功");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (sos != null) {
                try {
                    sos.close();
                } catch (IOException e) {
                    log.info("close outputstream fail:" + e);
                }
            }
        }
    }

    /**
     * 通過objectid刪除檔案
     * @param objectId
     */
    public static void deleteByObjectId(String objectId) {
        GridFSBucket bucket = GridFSBuckets.create(getDatabase());
        bucket.delete(new ObjectId(objectId));
        log.info("mongdb檔案刪除成功");
    }


    /**
     * 查詢檔案
     */
    public static List find(){
        GridFSBucket bucket = GridFSBuckets.create(getDatabase());
        GridFSFindIterable iterable = bucket.find();
        MongoCursor mongoCursor= iterable.iterator();
        List results = new ArrayList();
        while(mongoCursor.hasNext()){
            results.add(mongoCursor.next());
        }
        return results;
    }

    /**
     * 通過條件查詢檔案
     */
    public static List findBy(Bson filter){
        GridFSBucket bucket = GridFSBuckets.create(getDatabase());
        GridFSFindIterable iterable = bucket.find(filter);
        MongoCursor mongoCursor= iterable.iterator();
        List results = new ArrayList();
        while(mongoCursor.hasNext()){
            results.add(mongoCursor.next());
        }
        return results;
    }
}

加使用者名稱和密碼驗證

private static class Config {

        public static String host = null;
        public static String port = null;
        public static String username = null;
        public static String password = null;
        public static String database = null;
        public static String temporaryFile_dir = null;

        static {
            host = properties.getProperty("spring.data.mongodb.host");
            port = properties.getProperty("spring.data.mongodb.port");
            username = properties.getProperty("spring.data.mongodb.username");
            password = properties.getProperty("spring.data.mongodb.password");
            database =properties.getProperty("spring.data.mongodb.database");
            temporaryFile_dir =properties.getProperty("temporaryFile_dir");
        }
    }

    //連線mongdb
    private static final class MongoInstance {
        public static MongoClient client;

        static {
            try {
                //連線資料庫 start
                MongoCredential credential = MongoCredential.createCredential(Config.username, Config.database, Config.password.toCharArray());
                ServerAddress serverAddress;
                serverAddress = new ServerAddress(Config.host, Integer.parseInt(Config.port));
                List<ServerAddress> addrs = new ArrayList<ServerAddress>();
                addrs.add(serverAddress);
                List<MongoCredential> credentials = new ArrayList<MongoCredential>();
                credentials.add(credential);
                client = new MongoClient(addrs,credentials);
                log.info("mongdb連結成功");
                //連線資料庫 end
            } catch (Exception e) {
                log.error( e.getClass().getName() + ": " + e.getMessage() );
            }

        }
    }

    //連線資料庫
    public static MongoDatabase getDatabase() {
        return MongoInstance.client.getDatabase(Config.database);
    }

前端傳送請求

 window.open('preview/previewFile?fileName='+print,'top=0, left=0,height='+window.innerHeight+',width='+window.innerWidth+',resizable=yes,location=no');

輸出到前端預覽

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Map;

/**
 * @version 1.0
 * @description
 * @date 2018/6/20 13:29
 * @modified
 */
@RestController
@RequestMapping("/preview")
public class StatisticalLicenseController {
  
    /**
     * 證照管理預覽證照
     * @param user
     * @param params
     */
    @RequestMapping(value = "/previewFile", method = RequestMethod.GET)
    public void previewManageLicense(HttpServletRequest request,HttpServletResponse response, @ModelAttribute(SessionUser.TOKEN) SessionUser user, @RequestParam Map<String,String> params) throws IOException {
        JSONObject json = (JSONObject) JSONObject.toJSON(params);
        String  fileName= URLDecoder.decode(json.getString("fileName"),"UTF-8");
        MongoDbFSUtil.downloadFile2(fileName,response);
    }
}