【问题标题】:How to write file on Google App Engine?如何在 Google App Engine 上写入文件?
【发布时间】:2014-04-23 20:06:08
【问题描述】:

我想以编程方式在 Google App Engine 上下载和保存图像文件。我可以看到有一个 Datastore API,所以我可以保存任何对象。

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

但我需要将下载的图像 (byte[]) 保存到某个地方,以便在 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));

【问题讨论】:

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


    【解决方案1】:

    免费解决方案:

    • 如果图像小于 1MB,您可以将字节存储到数据存储区。
    • 您始终可以通过 API 使用第 3 方免费图片托管解决方案

    付费解决方案:

    否则,Google 建议您改用 Google Cloud Storage https://cloud.google.com/products/cloud-storage/

    由于不推荐直接写入 blobstore https://developers.google.com/appengine/docs/java/blobstore/#Java_Writing_files_to_the_Blobstore

    【讨论】:

    • 我找到了相同的“解决方案” :( 感谢您的回复!
    猜你喜欢
    • 2012-01-02
    • 2019-06-01
    • 2015-03-20
    • 2020-12-01
    • 1970-01-01
    • 2010-10-18
    • 1970-01-01
    • 1970-01-01
    • 2010-09-10
    相关资源
    最近更新 更多