inserting image into mongo from java result in a s

2019-06-12 16:49发布

I have the following code for saving image in mongodb:

    public static void insertImage() throws Exception {
    String newFileName = "mkyong-java-image";
    File imageFile = new File("c:\\JavaWebHosting.png");
    GridFS gfsPhoto = new GridFS(db, "photo");
    GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
    gfsFile.setFilename(newFileName);
    gfsFile.save();
}

And I got this from this link:

link for code

But when I use that I get the following error and I do not know how to fix it ... Can anyone help?

Exception in thread "main" java.lang.NullPointerException
at com.mongodb.gridfs.GridFS.<init>(GridFS.java:97)

for more explanation the error is at exactly this line:

GridFS gfsPhoto = new GridFS(db, "photo");

Update: Here is the code for creating db connection

     public static DB getDBConnection() {

    // If it's not connected to the database, make connection
    if (db == null) {
        initialize();
        makeConnections();
    }

    return db;
}


private static void makeConnections() {
    MongoCredential credential = MongoCredential.createMongoCRCredential(dbUser, dbName, dbPass.toCharArray());
    MongoClient mongoClient;

    try {
        mongoClient = new MongoClient(new ServerAddress(dbHost, Integer.parseInt(dbPort)), Arrays.asList(credential));
        db = mongoClient.getDB(dbName);
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
}

Update:

String newFileName = "mkyong-java-image";
    File imageFile = new File("D:/1.jpg");
    db = MongoDB.getDBConnection();
    collection = db.getCollection("test");

    // create a "photo" namespace
    GridFS gfsPhoto = new GridFS(db, "photo");

    // get image file from local drive
    GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);

    // set a new filename for identify purpose
    gfsFile.setFilename(newFileName);

    // save the image file into mongoDB
    gfsFile.save();

    // print the result
    DBCursor cursor = gfsPhoto.getFileList();
    while (cursor.hasNext()) {
        System.out.println(cursor.next());
    }

    // get image file by it's filename
    GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);

    // save it into a new image file
    imageForOutput.writeTo("D:\\JavaWebHostingNew.jpg");

    // remove the image file from mongoDB
    // gfsPhoto.remove(gfsPhoto.findOne(newFileName));

    System.out.println("Done");

0条回答
登录 后发表回答