0

我正在尝试将图像保存在我的应用程序中。但是当我尝试持久化图像对象时出现空指针异常。这是我的图像类:

 @PersistenceCapable
 public class ImageObject {

     @PrimaryKey
     @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
     private Key key;

     @Persistent
     private String title;

     @Persistent
     private Blob image;

     public ImageObject(){}

 //     all getters and setters
 }

以下是我的 servlet 代码,它给出了异常:

    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();
    PersistenceManager pm = PMF.get().getPersistenceManager();
    Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(req);
    List<BlobKey> blobKeyList = blobs.get("upload_img_form_input");
    BlobKey blobKey = blobKeyList.get(0);
    String keyString = req.getParameter("upload_img_form_key");

    Key key = KeyFactory.createKey(ImageObject.class.getSimpleName(), keyString);
    Image img = ImagesServiceFactory.makeImageFromBlob(blobKey);
    ImageObject imgObj = new ImageObject();
    imgObj.setKey(key);
    imgObj.setTitle(keyString);
    imgObj.setImage(img.getImageData());
// i am getting exception at this line where i am trying to persist 
    pm.makePersistent(imgObj);

谁能告诉我为什么我会得到这个 NullPointerException?提前致谢。

4

2 回答 2

0

你可以在这条线上拥有 Npe 的唯一方法:

pm.makePersistent(imgObj);

是当 pm 为空时

你应该检查那部分:

PersistenceManager pm = PMF.get().getPersistenceManager();

你的 persistence.xml 在类路径中吗?

于 2012-10-23T15:09:17.640 回答
0

根据我的经验,当您从中获取图像而不对其进行任何转换时会img.getImageData()返回。如果您想在不进行任何图像转换的情况下从 blob 中获取字节,则实际上不需要图像服务,您只需从 blob 存储中获取数据。我从博客文章中尝试了这段代码,它运行良好。nullImagesServiceFactory.makeImageFromBlob

public static byte[] readBlobFully(BlobKey blobKey) {

    BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
    BlobInfo blobInfo = new BlobInfoFactory().loadBlobInfo(blobKey);

    if (blobInfo == null)
        return null;

    if (blobInfo.getSize() > Integer.MAX_VALUE)
        throw new RuntimeException("This method can only process blobs up to " + Integer.MAX_VALUE + " bytes");

    int blobSize = (int) blobInfo.getSize();
    int chunks = (int) Math.ceil(((double) blobSize / BlobstoreService.MAX_BLOB_FETCH_SIZE));
    int totalBytesRead = 0;
    int startPointer = 0;
    int endPointer;
    byte[] blobBytes = new byte[blobSize];

    for (int i = 0; i < chunks; i++) {

        endPointer = Math.min(blobSize - 1, startPointer + BlobstoreService.MAX_BLOB_FETCH_SIZE - 1);

        byte[] bytes = blobstoreService.fetchData(blobKey, startPointer, endPointer);

        for (int j = 0; j < bytes.length; j++)
            blobBytes[j + totalBytesRead] = bytes[j];

        startPointer = endPointer + 1;
        totalBytesRead += bytes.length;
    }

    return blobBytes;
}
于 2014-08-26T08:22:01.567 回答