mongo db gridfs在play framework 2.3.x java中抛出空指针异常

时间:2014-11-10 07:31:47

标签: java mongodb playframework gridfs morphia

我关注此链接:mongoDBgridfs。我正在使用确切的代码。但在执行blob方法时,它会给出空指针异常。在这一行

    newUser.photo = new Blob(file, type);

但是图像存在,我确信图片路径是正确的,路径中没有错误。还有一点需要注意的是:当我给出错误的路径时,它会在数据库中保存一个空对象。所以它也不是数据库连接问题。我不明白为什么会这样。他们在文档中是错误还是什么?

    @Document(collection = "newuser")
    public class NewUser extends Model {

   public String firstName;
   public String lastName;
   public Blob photo;
   DB db;


public static String fileExtension(String fileName) {
    int mid= fileName.lastIndexOf(".");
    return fileName.substring(mid+1, fileName.length());
}
// photo upload handler
public static  void uploadPhoto( java.io.File file) throws IOException {
    System.out.println(file);
    NewUserRepository newUserRepository=new NewUserRepository();
    NewUser newUser=new NewUser();
   // String desc="etc";
   // GridFsHelper.storeFile(desc,file);
    String type = "image/" + NewUser.fileExtension(file.getName());
    System.out.println("type"+type);
   newUser.photo = new Blob(file, type);

//    newUserRepository.save(newUser);
}

public  GridFS getGridFS() {

    return new GridFS(db);
}

// fetch photo
public static void getPhoto(String userId) {
    NewUserRepository newUserRepository=new NewUserRepository();


}}

我的控制器是

    public static Result gridFsDemoIndex() {
 java.io.File file=new java.io.File("/Users/rajeshbansal/pics/demo2.jpg");

    try {

        NewUser.uploadPhoto(file);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return ok("gridfs worked");
}

出现的例外是

    java.lang.NullPointerException: null
    at leodagdag.play2morphia.Blob.set(Blob.java:50) ~[play2-morphia-plugin_2.9.1-0.0.6.jar:0.0.6]
    at leodagdag.play2morphia.Blob.<init>(Blob.java:34) ~[play2-morphia-plugin_2.9.1-0.0.6.jar:0.0.6]
    at controllers.gridfsdemo.NewUser.uploadPhoto(NewUser.java:37) ~[na:na]
    at controllers.Application.gridFsDemoIndex(Application.java:27) ~[na:na]
    at 

请帮帮我。

1 个答案:

答案 0 :(得分:0)

数据库连接存在问题。我正在将mongo与morphia模块合并,但没有将数据库设置提供给morphia.then我决定只使用mongo db并按照此链接

http://howtodoinjava.com/2014/07/23/java-mongodb-getsave-image-using-gridfs-apis/.its已完成