如何在Google App Engine上编写文件?

时间:2014-04-23 20:06:09

标签: java google-app-engine google-cloud-datastore blobstore

我想在Google App Engine上下载并保存图像文件。我可以看到有一个数据存储区API,所以我可以保存任何对象。

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

但我需要将下载的图像(byte [])保存到某个地方,我可以在HTML上下文中引用,例如src=static/image1.png。这听起来就像Blobstore。

我找到了很多上传示例,但我不想要上传表单。所以我尝试编译一个POST,就像文件upload example一样,但我没有工作。在谷歌应用引擎上没有更简单的文件保存解决方案(免费,因此云存储不是一个选项)?

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 个答案:

答案 0 :(得分:1)

免费解决方案:

  • 如果图像小于1MB,则可以将字节存储到数据存储区。
  • 您可以随时使用带有API的第三方免费图片托管解决方案

付费解决方案:

Othewise,Google建议您改用Google云端存储 https://cloud.google.com/products/cloud-storage/

直接写入blobstore是不推荐使用的 https://developers.google.com/appengine/docs/java/blobstore/#Java_Writing_files_to_the_Blobstore