简体   繁体   中英

Android upload image to Blobstore from Google Endpoints

I use Google Endpoints for my Android application. I want to upload an image to Blobstore:

Endpoint to get upload url:

@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
    }

Code in Android app to upload image:

        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();
        }

How do I get the final URL of the image?

Once the file is uploaded to the blobstore you can generate and return the serving URL as JSON like this:

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());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM