简体   繁体   English

如何使用谷歌应用引擎上传和存储图像(java)

[英]How to upload and store an image with google app engine (java)

I am looking for the simplest way to upload and store an image (file) to the GAE (java). 我正在寻找上传和存储图像(文件)到GAE(java)的最简单方法。 Googling for hours without any simple and clear result... : ( 谷歌搜索几个小时没有任何简单明了的结果... :(

Found this link . 找到这个链接

But I still don't know how to store an image, and how to retrieve it... I am looking for simple servlet exmample... 但我仍然不知道如何存储图像,以及如何检索它...我正在寻找简单的servlet exmample ......

The link your provided "How do I handle file uploads to my app?" 您提供的链接“我如何处理文件上传到我的应用程序?” explains how you can upload the image. 解释了如何上传图像。

To host the images, you need to use the Datastore service to store and serve image along with your other data. 要托管图像,您需要使用数据存储区服务来存储和提供图像以及其他数据。

Here is a sample code. 这是一个示例代码。 It is meant as a sketch, for how you can have your own entity (ig business, user, etc) have a field for an image. 它是一个草图,表示如何让自己的实体(ig业务,用户等)拥有图像的字段。 I ignored all error handling and recovery to simplify the code. 我忽略了所有错误处理和恢复以简化代码。

Declaring your entity with the image. 用图像声明您的实体。 You can imagine having other fields, eg tags, location, etc 您可以想象有其他字段,例如标签,位置等

@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; }
}

Then when you start accepting images (watch out for cases where an image with the same name has already been uploaded in addition to the typical file upload failures). 然后,当您开始接受图像时(注意除了典型的文件上载失败之外,已经上传了具有相同名称的图像的情况)。 ServletFileUpload and IOUtils are classes that are part of the Apache Commons library. ServletFileUploadIOUtils是属于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());
}

And finally when you want to serve an image given its name: 最后,当你想要提供一个给出名字的图像时:

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());
}

Use the blobstore API : 使用blobstore API

The Blobstore API allows your application to serve data objects, called blobs , that are much larger than the size allowed for objects in the Datastore service. Blobstore API允许您的应用程序提供称为blob的数据对象,这些对象远大于Datastore服务中对象所允许的大小。 Blobs are useful for serving large files, such as video or image files, and for allowing users to upload large data files. Blob对于提供大型文件(如视频或图像文件)以及允许用户上载大型数据文件非常有用。 Blobs are created by uploading a file through an HTTP request. 通过HTTP请求上载文件来创建Blob。 Typically, your applications will do this by presenting a form with a file upload field to the user. 通常,您的应用程序将通过向用户显示带有文件上载字段的表单来完成此操作。 When the form is submitted, the Blobstore creates a blob from the file's contents and returns an opaque reference to the blob, called a blob key , which you can later use to serve the blob. 提交表单时,Blobstore会根据文件的内容创建一个blob,并返回对blob的不透明引用,称为blob键 ,稍后您可以使用它来提供blob。 The application can serve the complete blob value in response to a user request, or it can read the value directly using a streaming file-like interface... 应用程序可以响应用户请求提供完整的blob值,或者它可以使用类似流文件的接口直接读取值...

Easiest way to use Google App Engine Blob Store serving URL (you save instance time) 使用Google App Engine Blob商店服务网址的最简单方法(节省实例时间)

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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用Java以编程方式将图像上传到Google App Engine Blobstore - Upload an image to google app engine blobstore with java programmatically 如何使用Java App Engine正确上传(映像)文件到Google云端存储? - How to properly upload (image) file to Google Cloud Storage using Java App Engine? 如何从URL检索图像并将其存储为Java中的Blob(Google App引擎) - How to I retrieve an image from a URL and store it as a Blob in Java (google app engine) 如何使用javaGUI(java应用程序)将文件上传到Google App Engine - How to upload a file by using javaGUI(java application) to google app engine 本地图片上传未显示在Google App Engine上 - local image upload not showing on Google App Engine 如何在Google App Engine Objectify中存储地图的ArrayList对象(java) - How to store ArrayList of Maps in Google App Engine objectify (java) Google App Engine异步图片上传 - Google App Engine asynchronous image upload Google App Engine和Java:将文件上传到Blobstore - Google App Engine & Java : upload files into the blobstore 用Java进行单元测试App Engine图像上传 - Unit testing app engine image upload in Java 通过Google App Engine(JAVA)将文件(图像或视频)从JSP上传到Google云存储 - Upload File (image or video) from JSP to google cloud storage via Google app engine(JAVA)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM