【问题标题】:google app engine url fetch service iurl issue谷歌应用引擎 url 获取服务 iurl 问题
【发布时间】:2012-03-31 05:40:18
【问题描述】:

我想使用 Google 应用引擎和 JDO 将一张图片上传到数据库。 我从网上得到了一个代码。

http://code.google.com/appengine/articles/java/serving_dynamic_images.html

我试过那个例子。但是我传递给 URLFetchService fetch 方法的 url 抛出了格式错误的异常。所以这里应该预期这个 url 值是多少。 我把url值的值作为jsp页面的文件上传值。

请在下面找到代码:

package com.google.appengine.demo.domain;

import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.Key;

import javax.jdo.annotations.Extension;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

/**
 * JDO-annotated model class for storing movie properties; movie's promotional
 * image is stored as a Blob (large byte array) in the image field.
 */
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Movie {

    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key key;

    @Persistent
    private String title;

    @Persistent
    @Extension(vendorName="datanucleus", key="gae.unindexed", value="true")
    private String imageType;

    @Persistent
    private Blob image;



    public Long getId() {
        return key.getId();
    }

    public String getTitle() {
        return title;
    }

    public String getImageType() {
        return imageType;
    }

    public byte[] getImage() {
        if (image == null) {
            return null;
        }

        return image.getBytes();
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setImageType(String imageType) {
        this.imageType = imageType;
    }

    public void setImage(byte[] bytes) {
        this.image = new Blob(bytes);
    }

    //...
}

JSP

<html>

<head>
<title>Image Upload</title>
</head>

<body>
    <form action="/addMovie" method="get" enctype="multipart/form-data"
        name="productForm" id="productForm">
        <br>
        <br>
        <table width="400px" align="center" border=0
            style="background-color: ffeeff;">
            <tr>
                <td align="center" colspan=2
                    style="font-weight: bold; font-size: 20pt;">Image Details</td>
            </tr>

            <tr>
                <td align="center" colspan=2>&nbsp;</td>
            </tr>

            <tr>
                <td>Image Link:</td>
                <td><input type="file" name="url" ><td>
            </tr>

            <tr>
                <td></td>
                <td><input type="submit" name="Submit" value="Submit">
                </td>
            </tr>
            <tr>
                <td colspan="2">&nbsp;</td>
            </tr>

        </table>
    </form>
</body>

</html>

小服务程序

package com.google.appengine.demo.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pmf.PMF;

import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;
import com.google.appengine.demo.domain.Movie;

/**
 * GET requests fetch the image at the URL specified by the url query string
 * parameter, then persist this image along with the title specified by the
 * title query string parameter as a new Movie object in App Engine's
 * datastore.
 */
public class StoreMovieServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;



     public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws IOException {


            PrintWriter out = response.getWriter();
            try {          
               String url1 = request.getParameter("url");           
               String url ="http://localhost:8877/addMovie?url="+url1;

             //  url = "C:\\my_photo.jpg";

               System.out.println("url:: +"+url);            
               URLFetchService fetchService =
                   URLFetchServiceFactory.getURLFetchService();
               HTTPResponse fetchResponse = fetchService.fetch(new URL(
                       request.getParameter(url1)));
               String fetchResponseContentType = null;
               for (HTTPHeader header : fetchResponse.getHeaders()) {
                   // For each request header, check whether the name equals
                   // "Content-Type"; if so, store the value of this header
                   // in a member variable
                   if (header.getName().equalsIgnoreCase("content-type")) {
                       fetchResponseContentType = header.getValue();
                       break;
                   }
               }     
               Movie movie = new Movie();
              // movie.setTitle(req.getParameter("title"));
               movie.setImageType(fetchResponseContentType);

               // Set the movie's promotional image by passing in the bytes pulled
               // from the image fetched via the URL Fetch service
               movie.setImage(fetchResponse.getContent());
               PersistenceManager pm = PMF.get().getPersistenceManager();
               try {
                   // Store the image in App Engine's datastore
                   pm.makePersistent(movie);
               } finally {
                   pm.close();
               }



            }catch(Exception ex){
                ex.printStackTrace();
            }
            finally {            
                out.close();
            }


     }



    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        PrintWriter out = response.getWriter();
        try {          
           String url1 = request.getParameter("url");           
           String url ="http://localhost:8877/addMovie?url="+url1;

         //  url = "C:\\my_photo.jpg";

           System.out.println("url:: +"+url);            
           URLFetchService fetchService =
               URLFetchServiceFactory.getURLFetchService();
           HTTPResponse fetchResponse = fetchService.fetch(new URL(
                   request.getParameter(url1)));
           String fetchResponseContentType = null;
           for (HTTPHeader header : fetchResponse.getHeaders()) {
               // For each request header, check whether the name equals
               // "Content-Type"; if so, store the value of this header
               // in a member variable
               if (header.getName().equalsIgnoreCase("content-type")) {
                   fetchResponseContentType = header.getValue();
                   break;
               }
           }     
           Movie movie = new Movie();
          // movie.setTitle(req.getParameter("title"));
           movie.setImageType(fetchResponseContentType);

           // Set the movie's promotional image by passing in the bytes pulled
           // from the image fetched via the URL Fetch service
           movie.setImage(fetchResponse.getContent());
           PersistenceManager pm = PMF.get().getPersistenceManager();
           try {
               // Store the image in App Engine's datastore
               pm.makePersistent(movie);
           } finally {
               pm.close();
           }



        }catch(Exception ex){
            ex.printStackTrace();
        }
        finally {            
            out.close();
        }

    }

    private void storeImage(HttpServletRequest req) throws IOException,
            MalformedURLException {
        URLFetchService fetchService =
            URLFetchServiceFactory.getURLFetchService();

        // Fetch the image at the location given by the url query string parameter
        HTTPResponse fetchResponse = fetchService.fetch(new URL(
                req.getParameter("url")));

        String fetchResponseContentType = null;
        for (HTTPHeader header : fetchResponse.getHeaders()) {
            // For each request header, check whether the name equals
            // "Content-Type"; if so, store the value of this header
            // in a member variable
            if (header.getName().equalsIgnoreCase("content-type")) {
                fetchResponseContentType = header.getValue();
                break;
            }
        }

        if (fetchResponseContentType != null) {
            // Create a new Movie instance
            Movie movie = new Movie();
            movie.setTitle(req.getParameter("title"));
            movie.setImageType(fetchResponseContentType);

            // Set the movie's promotional image by passing in the bytes pulled
            // from the image fetched via the URL Fetch service
            movie.setImage(fetchResponse.getContent());

            //...

            PersistenceManager pm = PMF.get().getPersistenceManager();
            try {
                // Store the image in App Engine's datastore
                pm.makePersistent(movie);
            } finally {
                pm.close();
            }
        }
    }

web.xml

<servlet>
    <servlet-name>StoreMovie</servlet-name>
    <servlet-class>com.google.appengine.demo.web.StoreMovieServlet</servlet-class>
</servlet>
<servlet>
    <servlet-name>GetImage</servlet-name>
    <servlet-class>com.google.appengine.demo.web.GetImageServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>StoreMovie</servlet-name>
    <url-pattern>/addMovie</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>GetImage</servlet-name>
    <url-pattern>/image</url-pattern>
</servlet-mapping>

【问题讨论】:

    标签: java google-app-engine servlets google-cloud-datastore jdo


    【解决方案1】:

    您发布的示例代码是从 URL 获取图像,而您的代码正在尝试从文件系统上传图像。

    &lt;input type="file"&gt; 表示您正在从本地系统中选择它。这不会转换为 URL。您将把这张图片上传到 App Engine,然后用它做任何你想做的事情。

    Here 很好地介绍了如何使用 Apache Commons File Upload jar 来做到这一点。

    【讨论】:

    • 好的。非常感谢!!。还有一个问题。那么如果我想通过GAE将图像从本地系统上传到数据存储区,我需要使用Apache commons File Upload jars吗?没有 Apache Commons 文件上传 jar,这不可能吗?我不想将第三方库添加到我的项目中。
    • 是的。看起来那是唯一的选择。甚至 GAE 的官方文档也提到了文件上传。 code.google.com/appengine/kb/java.html#fileforms
    • 好的。然后我按照这个 apache 文件上传。
    猜你喜欢
    • 2013-09-04
    • 1970-01-01
    • 2012-03-22
    • 1970-01-01
    • 2015-10-20
    • 2011-01-30
    • 1970-01-01
    • 2015-01-12
    • 1970-01-01
    相关资源
    最近更新 更多