java原生代碼實現MongoDB的文件上傳及下載


一、pom依賴(MongoDB驅動)

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver</artifactId>
    <version>3.4.2</version>
</dependency>

二、獲取核心對象(GridFSBucket)

    private final static String URL = "127.0.0.1";
    private final static Integer PORT = 27017;
    private final static String DATABASE = "liuli";
private static MongoClient client; private static MongoDatabase db; private static GridFSBucket bucket; static{ MongoClientOptions options = MongoClientOptions.builder().build(); ServerAddress address = new ServerAddress(URL, PORT); client = new MongoClient(address, options); db = client.getDatabase(DATABASE); /*后面的名字可以自定義 * MongoDb會在數據庫生成兩個collections(users.chunks和users.files) * users.files存放文件信息 * users.chunks存放文件的二進制流 */ bucket = GridFSBuckets.create(db,"users"); }

三、文件上傳

    /**
     * 文件上傳
     */
    public void fileUp(){
        File png = new File("C:\\Users\\mayn\\Desktop\\1.png");
        GridFSUploadOptions options = null;
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(png);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Document document = new Document();
        document.put("name", "liuli");
        //metadata方法可以為文件上傳的同時附加一些元數據
        options = new GridFSUploadOptions().chunkSizeBytes(358400).metadata(document);
        ObjectId id = bucket.uploadFromStream("1.png", inputStream, options);
        System.out.println("objectid="+id);
    }

四、獲取文件的一些屬性

    /**
     * 查詢文件屬性
     */
    public void fileDown(){
        bucket.find().forEach(new Block<GridFSFile>() {

            @Override
            public void apply(GridFSFile t) {
                //GridFSFile封裝了所有字段
                System.out.println(t.getFilename());
            }
            
        });
    }

在MongoDB客戶端我們可以看到它的內容是這樣的

五、文件下載

    /**
     * 下載文件
     * @throws FileNotFoundException 
     */
    public void fileDownLoad() throws FileNotFoundException{
        bucket.downloadToStream("1.png", new FileOutputStream(new File("src\\main\\resources\\2.png")));
    }

我們可以看到文件夾中有了該文件

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM