1

我尝试使用文件服务将数据存储在 Google 应用程序引擎中,并且我成功上传了它,但后来我注意到它没有存储为 blob 值。所以我用谷歌搜索并得到了这个链接如何处理多部分表单数据?或如何处理文件上传到我的应用程序?由谷歌提供。

在本文档中,代码如下所示,

 FileItemIterator iterator = upload.getItemIterator(req);
 while (iterator.hasNext()) {
 FileItemStream item = iterator.next();
 InputStream stream = item.openStream();
 if (item.isFormField()) {
 log.warning("Got a form field: " + item.getFieldName());
 } else {
 log.warning("Got an uploaded file: " + item.getFieldName() +", name = " + item.getName());

 // You now have the filename (item.getName() and the
 // contents (which you can read from stream). Here we just
 // print them back out to the servlet output stream, but you
 // will probably want to do something more interesting (for
 // example, wrap them in a Blob and commit them to the
 // datastore).

这里我不了解如何将它们包装为 blob 并将它们提交到数据存储区。谁能建议我如何解决这个问题。这种方式是否将文件存储为谷歌应用引擎中的 blob 值?

4

1 回答 1

1
InputStream is = item.openStream();
try {
   FileService fileService = FileServiceFactory.getFileService();
   AppEngineFile file = fileService.createNewBlobFile(mime, fileName);
   boolean lock = true;
   FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);
   byte[] buffer = new byte[BUFFER_SIZE];
   int readBytes;
   while ((readBytes = is.read(buffer)) != -1) {
       writeChannel.write(ByteBuffer.wrap(buffer, 0, readBytes));
   }
   writeChannel.closeFinally();
   String blobKey = fileService.getBlobKey(file).getKeyString();
} catch (Exception e) {
   e.printStackTrace(resp.getWriter());
}
于 2013-01-29T17:34:06.003 回答