69

我正在寻找将图像(文件)上传和存储到 GAE(java)的最简单方法。谷歌搜索了几个小时,没有任何简单明了的结果。

找到这个链接

但我仍然不知道如何存储图像,以及如何检索它。我正在寻找简单的 servlet 示例。

4

3 回答 3

96

您提供的链接“如何处理文件上传到我的应用程序?” 说明如何上传图像。

要托管图像,您需要使用Datastore 服务来存储和提供图像以及其他数据。

这是一个示例代码。它是一个草图,用于说明如何让自己的实体(例如企业、用户等)拥有一个图像字段。我忽略了所有错误处理和恢复以简化代码。

用图像声明你的实体。您可以想象有其他字段,例如标签、位置等

@Entity
public class MyImage {
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Long id;

    @Persistent
    private String name;

    @Persistent
    Blob image;

    public MyImage() { }
    public MyImage(String name, Blob image) {
        this.name = name; 
        this.image = image;
    }

    // JPA getters and setters and empty contructor
    // ...
    public Blob getImage()              { return image; }
    public void setImage(Blob image)    { this.image = image; }
}

然后当您开始接受图像时(除了典型的文件上传失败之外,还要注意已经上传了同名图像的情况)。 ServletFileUpload并且IOUtils是属于 Apache Commons 库的类。

// Your upload handle would look like
public void doPost(HttpServletRequest req, HttpServletResponse res) {
    // Get the image representation
    ServletFileUpload upload = new ServletFileUpload();
    FileItemIterator iter = upload.getItemIterator(req);
    FileItemStream imageItem = iter.next();
    InputStream imgStream = imageItem.openStream();

    // construct our entity objects
    Blob imageBlob = new Blob(IOUtils.toByteArray(imgStream));
    MyImage myImage = new MyImage(imageItem.getName(), imageBlob);

    // persist image
    PersistenceManager pm = PMF.get().getPersistenceManager();
    pm.makePersistent(myImage);
    pm.close();

    // respond to query
    res.setContentType("text/plain");
    res.getOutputStream().write("OK!".getBytes());
}

最后,当你想提供一个给定名称的图像时:

Blob imageFor(String name, HttpServletResponse res) {
    // find desired image
    PersistenceManager pm = PMF.get().getPersistenceManager();
    Query query = pm.newQuery("select from MyImage " +
        "where name = nameParam " +
        "parameters String nameParam");
    List<MyImage> results = (List<MyImage>)query.execute(name);
    Blob image = results.iterator().next().getImage();

    // serve the first image
    res.setContentType("image/jpeg");
    res.getOutputStream().write(image.getBytes());
}
于 2009-10-03T17:17:45.740 回答
10

使用blobstore API

Blobstore API 允许您的应用程序提供数据对象(称为blobs),其大小远大于数据存储服务中对象所允许的大小。Blob 对于提供大文件(例如视频或图像文件)以及允许用户上传大数据文件很有用。Blob 是通过 HTTP 请求上传文件来创建的。通常,您的应用程序将通过向用户显示带有文件上传字段的表单来完成此操作。提交表单后,Blobstore 会根据文件的内容创建一个 blob,并返回对该 blob 的不透明引用,称为blob key,您以后可以使用它来提供 blob。应用程序可以响应用户请求提供完整的 blob 值,或者它可以使用类似流文件的接口直接读取值...

于 2010-06-29T07:07:20.370 回答
5

使用 Google App Engine Blob Store 服务 URL 的最简单方法(节省实例时间)

import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileWriteChannel;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.ServingUrlOptions;
...


// your data in byte[] format
byte[] data = image.getData();
/**
 *  MIME Type for
 *  JPG use "image/jpeg" for PNG use "image/png"
 *  PDF use "application/pdf"
 *  see more: https://en.wikipedia.org/wiki/Internet_media_type
 */
String mimeType = "image/jpeg";

// save data to Google App Engine Blobstore 
FileService fileService = FileServiceFactory.getFileService();
AppEngineFile file = fileService.createNewBlobFile(mimeType); 
FileWriteChannel writeChannel = fileService.openWriteChannel(file, true);
writeChannel.write(java.nio.ByteBuffer.wrap(data));
writeChannel.closeFinally();

// your blobKey to your data in Google App Engine BlobStore
BlobKey blobKey = fileService.getBlobKey(file);

// THANKS TO BLOBKEY YOU CAN GET FOR EXAMPLE SERVING URL FOR IMAGES

// Get the image serving URL (in https:// format)
String imageUrl =
  ImagesServiceFactory.getImagesService().getServingUrl(
    ServingUrlOptions.Builder.withBlobKey(blobKey
          ).secureUrl(true));
于 2013-04-28T09:38:11.640 回答