MongoDB
 sql >> Teknologi Basis Data >  >> NoSQL >> MongoDB

Bagaimana cara menyisipkan gambar di mongoDB menggunakan java?

Untuk menyimpan data biner seperti gambar, Anda dapat menggunakan GridFS atau menerapkan realisasi Anda sendiri; Unduh driver dan lihat src/test/com/mongodb/gridfs/GridFSTest.java;)

Sunting:Anda beruntung hari ini! Saya membuat kode lengkap untuk Anda;) Selamat menikmati!

package mongodb.testing.java;
import com.mongodb.*;
import com.mongodb.gridfs.*;
import java.io.*;

public class Main {

    public static byte[] LoadImage(String filePath) throws Exception {
        File file = new File(filePath);
        int size = (int)file.length();
        byte[] buffer = new byte[size];
        FileInputStream in = new FileInputStream(file);
        in.read(buffer);
        in.close();
        return buffer;
    }

    public static void main(String[] args) throws Exception {
        //Load our image
        byte[] imageBytes = LoadImage("C:/Temp/bear.bmp");
        //Connect to database
        Mongo mongo = new Mongo( "127.0.0.1" );
        String dbName = "GridFSTestJava";
        DB db = mongo.getDB( dbName );
        //Create GridFS object
        GridFS fs = new GridFS( db );
        //Save image into database
        GridFSInputFile in = fs.createFile( imageBytes );
        in.save();

        //Find saved image
        GridFSDBFile out = fs.findOne( new BasicDBObject( "_id" , in.getId() ) );

        //Save loaded image from database into new image file
        FileOutputStream outputImage = new FileOutputStream("C:/Temp/bearCopy.bmp");
        out.writeTo( outputImage );
        outputImage.close();
    }
}


  1. Redis
  2.   
  3. MongoDB
  4.   
  5. Memcached
  6.   
  7. HBase
  8.   
  9. CouchDB
  1. Meteor, MongoDB dapatkan bagian dari array melalui berlangganan

  2. Mongodb:dapatkan hanya daun pohon

  3. Grup bersarang MongoDB?

  4. Pesan Kesalahan Kustom dengan Mongoose

  5. Mongoexport -q ISODate query