谷歌应用引擎urlfetch服务网址问题

时间:2012-03-14 17:59:28

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

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

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

我试过那个例子。但是我传递给URLFetchService fetch方法的url是抛出Malformed异常。那么这个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>

的Servlet

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>

1 个答案:

答案 0 :(得分:2)

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

<input type="file">表示您从本地系统中选择此项。这不会转换为URL。您将把这个图像上传到App Engine,然后随意做任何事情。

Here是如何使用Apache Commons File Upload jar进行的一个很好的演练。