1

我使用以下代码成功地将图像保存到 Datastore 中的 Blob:

@RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(ModelMap model, Product form, HttpServletRequest request) {
      if(ServletFileUpload.isMultipartContent(request)) { // if(form.getImage().getBytes().getSize() != 0) {
          try { 
              Blob file = new Blob(form.getImage().getBytes()); 
              form.setImg(file);
          } catch (IOException  e) { 
              e.printStackTrace(); 
          }
      }
 //save to datastore etc
}

我只是尝试将它保存在 BlobStore 中,然后将 Blob 密钥保存在数据存储中。有可能吗?这是我的片段,但没有作品:

@RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(ModelMap model, Product form, HttpServletRequest request) {
      Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(request);
      BlobKey blobKey = blobs.get("image");
      form.setImage1(blobKey); 
      //save to datastore etc
}

我从这个例子中学习。我得到了这个错误:

Must be called from a blob upload callback request.

堆栈跟踪 :

java.lang.IllegalStateException: Must be called from a blob upload callback request.
at com.google.appengine.api.blobstore.BlobstoreServiceImpl.getUploads(BlobstoreServiceImpl.java:160)
at com.google.appengine.api.blobstore.BlobstoreServiceImpl.getUploadedBlobs(BlobstoreServiceImpl.java:144)
at com.shop.controller.ProductController.add(ProductController.java:92)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
    ....

解决方案 :

最后我发现我需要在我的jsp中生成url:

<form:form action='<%=blobstoreService.createUploadUrl("/admin/product/add")%>' commandName="product" methodParam="POST" enctype="multipart/form-data">
4

1 回答 1

1

而不是保存 blobkey,尝试通过保存其字符串表示

 String blobStr = blobKey.getKeyString();

字符串表示可以很容易地序列化并保存在 DataStore 中。您总是可以从它们的字符串表示中构造回 BlobKey 实例

 BlobKey blobKey = new BlobKey(blobStr);
于 2013-05-21T10:54:09.207 回答