2010年8月30日 星期一

轉貼 FileUpload google app engine java(图片上传实例demo)

google appengine 可以用來儲存相當多的資料,不同於文字,若要儲存圖片的話就比較麻煩一些


以下轉貼自 http://mimaiji.appspot.com/article?method=view&id=9001


程式碼簡單分成四個部份

1. 圖片物件 Photo.java



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;

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


@PersistenceCapable(identityType = IdentityType.APPLICATION,detachable="true")
public class Photo {

@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Long id;

@SuppressWarnings("unused")
@Persistent
private String photoID;


@SuppressWarnings("unused")
@Persistent
private Blob photoO;


public Photo(Blob ObjBlob)
{
this.photoO = ObjBlob;
}



public Blob getPhoto() {
return this.photoO;
}

public Long getId() {
return this.id;
}


}






2. 資料存取物件 PhotoDao.java





import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

public class PhotoDao {
private static PhotoDao _instance = null;

public static PhotoDao getInstance() {
if (_instance == null) {
_instance = new PhotoDao();
}
return _instance;
}

public String insertPhoto(Photo photo) {
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
pm.makePersistent(photo);
} finally {
pm.close();
}
return photo.getId().toString();
}


public Photo getById(Long id) {
PersistenceManager pm = PMF.get().getPersistenceManager();
Query query = pm.newQuery(Photo.class);
query.setFilter("id == idParam");
query.declareParameters("Long idParam");
List photo = null;
try {
photo = (List) query.execute(id);
if (photo.isEmpty()){
return null;
}else{
return (Photo) photo.get(0);
}

} finally {
query.closeAll();
}
}
}





3. PhotoServlet.java, Servlet 的設定,
3-1.這個例子要 import Apache 的 "
commons-fileupload" 和 "commons-io"
3-2. 下載完解壓縮, eciplse 專案中 加入 external jar, 如圖


3-3. 兩個 jar 要放在 \war\lib 中

3-4. code




import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

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

public class PhotoServlet extends HttpServlet{
/*display image*/
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
String id = req.getParameter("id");
Photo photo = PhotoDao.getInstance().getById(Long.parseLong(id));
Blob b = photo.getPhoto();
resp.setContentType("image/jpeg;charset=utf-8");
resp.getOutputStream().write(b.getBytes());
resp.getOutputStream().close();
}
/*upload image and add to datastore*/
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iterator = null;
try {
iterator = upload.getItemIterator(req);
} catch (FileUploadException e) {
e.printStackTrace();
}
try {
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
InputStream stream = item.openStream();
if (item.isFormField()) {
// Handle form field
} else {
Blob bImg = new Blob(IOUtils.toByteArray(stream));
Photo photo = new Photo(bImg);
String pid = PhotoDao.getInstance().insertPhoto(photo);
req.setAttribute("Pid", pid);
resp.getWriter().write("Success "+ photo.getId());
}

}
} catch (FileUploadException e) {
e.printStackTrace();
}

}

}





4. 在 web.xml 設定 servelt 的路徑






<servlet>
<servlet-name>PhotoServlet</servlet-name>
<servlet-class>ppp.com.PhotoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PhotoServlet</servlet-name>
<url-pattern>/PhotoServlet</url-pattern>
</servlet-mapping>




附註: 要將資料抓到程式中的話
可以利用 HTTP GET 的方式,來取得圖片的 Stream


例如 C# 為例將資料存成 BitmapImage


private void GetHTTPRequest(string URL)
{
/// try send message to the web, if success show that the connect correct
try
{
/// Create the request obj
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URL);

/// Set values for the request back
req.Method = "GET";

BitmapImage Bi = new BitmapImage();

Bi.BeginInit();

/// Set Bi source from MemoryStream
Bi.StreamSource = req.GetResponse().GetResponseStream();

Bi.EndInit();

IMG.Source = Bi;

}

catch{
Console.WriteLine("Error");
}
}

沒有留言: