栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用Google App Engine(Java)上传和存储图像

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用Google App Engine(Java)上传和存储图像

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

解释了如何上传图像。

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

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

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

@Entitypublic 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的共享库的一部分课程。

// Your upload handle would look likepublic 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());}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/418986.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号