inserting image into mongo from java result in a strange error

萝らか妹 提交于 2019-12-08 12:38:51

问题


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");

来源:https://stackoverflow.com/questions/28554130/inserting-image-into-mongo-from-java-result-in-a-strange-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!