2014-04-23 59 views
0

我想要編程下載並將圖像文件保存在Google App Engine上。我可以看到有一個Datastore API,因此我可以保存任何對象。如何在Google App Engine上編寫文件?

Entity e = new Entity("Kind"); 
e.setProperty("heigh",6); 
DatastoreServiceFactory.getDatastoreService().put(e); 

但我需要保存下載的圖像(字節[])的某個地方,在那裏我可以一個HTML範圍內引用,就像src=static/image1.png。這聽起來就像Blobstore一樣。

我發現很多上傳的例子,但我不想要上傳表單。所以我試圖編寫一個POST,就像在文件upload example,但我不工作。在Google App Engine中沒有更簡單的文件保存解決方案(免費,因此雲存儲不是一種選擇)?

URL surl = new URL("http://www.freeonlinegames.com/games/39779/medium.jpg"); 
byte[] byteArray = URLFetchServiceFactory.getURLFetchService().fetch(surl).getContent(); 
StringBuilder parameters = new StringBuilder(); 

parameters.append("--BOUNDARY"); 
parameters.append("\nContent-Disposition: form-data; name=\"file\"; filename\"test.png\"\n"); 
parameters.append("Content-Type: image/jpg\n\n"); 

parameters.append(new String(byteArray)); 
parameters.append("\n--BOUNDARY\n"); 

String request = BlobstoreServiceFactory.getBlobstoreService().createUploadUrl("/upload"); 


URL durl = new URL(request); 
log("upload: " + durl.toString()); 

HttpURLConnection connection = (HttpURLConnection) durl.openConnection();   
connection.setDoOutput(true); 
connection.setDoInput(true); 

connection.setRequestMethod("POST"); 
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=--BOUNDARY"); 
connection.setRequestProperty("Content-Length",Integer.toString(parameters.toString().getBytes().length)); 
connection.setRequestProperty("Cache-Control","max-age=0"); 
        connection.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); 
connection.setRequestProperty("Accept-Encoding","gzip,deflate,sdch");     

DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); 

wr.writeBytes(parameters.toString()); 

wr.flush(); 
wr.close(); 

BufferedInputStream bis = new BufferedInputStream(connection.getInputStream()); 
byte[] bkey = new byte[512]; 
bis.read(bkey); 
log("resp: " + new String(bkey)); 

回答

1

免費的解決方案:

  • 如果超過1MB的圖片越少,你可以在字節存儲到數據存儲。
  • 您可以隨時使用第三方免費圖片託管與API

付費解決方案:

Othewise,谷歌建議你使用谷歌雲存儲,而不是 https://cloud.google.com/products/cloud-storage/

因爲寫入直接BLOBSTORE已棄用 https://developers.google.com/appengine/docs/java/blobstore/#Java_Writing_files_to_the_Blobstore

+1

我找到了相同的「解決方案」:(謝謝您的回覆! –

相關問題