Android从Google终端上传图片到Blobstore

时间:2015-01-10 20:23:48

标签: android google-cloud-endpoints blobstore

我将Android端点用于Android应用程序。我想将图像上传到Blobstore:

获取上传网址的端点:

@ApiMethod(name = "generateImageUploadUrl")
    public UploadUrl generateImageUploadUrl() {
        BlobstoreService blobstoreService =
                BlobstoreServiceFactory.getBlobstoreService();

        String blobUploadUrl = blobstoreService.createUploadUrl("/blob/upload");
        return new UploadUrl(blobUploadUrl); // UploadUrl is an inner class to store the url
    }

Android应用中的代码上传图片:

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(url);
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        try{
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 75, bos);
            byte[] data = bos.toByteArray();
            ByteArrayBody bab = new ByteArrayBody(data, "forest.jpg");
            reqEntity.addPart("picture", bab);

            postRequest.setEntity(reqEntity);
            HttpResponse response = httpClient.execute(postRequest);
            HttpEntity entity = response.getEntity();
            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
            String sResponse;
            StringBuilder s = new StringBuilder();
            while ((sResponse = reader.readLine()) != null) {
                s = s.append(sResponse);
            }

            s.toString();
        }
        catch(Exception e){
            e.getCause();
        }

如何获取图片的最终网址?

1 个答案:

答案 0 :(得分:0)

将文件上传到blobstore后,您可以生成并将服务URL作为JSON返回,如下所示:

public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException  {
    List<BlobKey> blobs = blobstoreService.getUploads(req).get("file");
    BlobKey blobKey = blobs.get(0);
    ImagesService imagesService = ImagesServiceFactory.getImagesService();
    ServingUrlOptions servingOptions = Builder.withBlobKey(blobKey);
    String servingUrl = imagesService.getServingUrl(servingOptions);

    res.setStatus(HttpServletResponse.SC_OK);
    res.setContentType("application/json");

    JSONObject json = new JSONObject();
    json.put("servingUrl", servingUrl);
    PrintWriter out = res.getWriter();
    out.print(json.toString());
}