简体   繁体   English

将图像从Android客户端发送到AppEngine Cloud Endpoint

[英]Send image from Android client to AppEngine Cloud Endpoint

I am developing an Android applicaiton with AppEngine backend. 我正在使用AppEngine后端开发Android应用程序。 I am creating the server part with Google Cloud Endpoints in Java. 我正在使用Java中的Google Cloud Endpoints创建服务器部分。 My problem is that I cannot send a Bitmap from the client to the server. 我的问题是我无法从客户端向服务器发送位图。

I used the answer from this question but even if the client part does not seem to have any problems at all, the server part does not receive the data at all. 我使用了这个问题的答案,但即使客户端部分似乎没有任何问题,服务器部分也根本不接收数据。 I also think this solution might be a bit complicated and that it might work a different, easier way, however this is my first time implementing a server and first time sending a picture to it so I accept any good tips on this. 我也认为这个解决方案可能有点复杂,它可能会以不同的,更简单的方式工作,但这是我第一次实现服务器并第一次向它发送图片,所以我接受任何有关此的好建议。 Thanks! 谢谢!

Here is my code: 这是我的代码:

        String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
        String CRLF = "\r\n"; // Line separator required by multipart/form-data.
        String charset = "UTF-8";

        HttpURLConnection connection = (HttpURLConnection) new URL("https://path_to_my_app/_ah/api/registration/v1/uploadImage").openConnection();
        connection.setDoOutput(true);
        connection.setReadTimeout(60000);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        PrintWriter writer = null;
        try {
            OutputStream output = connection.getOutputStream();
            writer = new PrintWriter(new OutputStreamWriter(output, charset), true); // true = autoFlush, important!

            // Send text file.
            writer.append("--" + boundary).append(CRLF);
            writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + somename + "\"").append(CRLF);
            writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
            writer.append(CRLF).flush();
            BufferedReader reader = null;

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            photo.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
            byteArray = stream.toByteArray();

            try {
                reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(byteArray), charset));
                for (String line; (line = reader.readLine()) != null;) {
                    writer.append(line).append(CRLF);
                }
            } finally {
                if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
            }
            writer.flush();


//            End of multipart/form-data.
        writer.append("--" + boundary + "--").append(CRLF);
    }
    finally
    {
        if (writer != null)
        {
            writer.close();
        }
    }

The server part: 服务器部分:

@ApiMethod(name = "uploadImage", httpMethod = "POST")
public void uploadImage(HttpServletRequest request, HttpServletResponse response) throws IOException
{
    ServletFileUpload fileUpload = new ServletFileUpload();
    try
    {
        FileItemIterator iterator = fileUpload.getItemIterator(request);

        while(iterator.hasNext()){
            FileItemStream itemStream = iterator.next();

            String fieldName = itemStream.getFieldName();
            log.info("field name:"+fieldName);

            InputStream stream = itemStream.openStream();

            String result = getStringFromInputStream(stream);
            log.info("result: "+result);

            stream.close();
        }
    }
    catch (FileUploadException e)
    {
        e.printStackTrace();
    }

} }

I am getting 204 no Content type now. 我现在得到204没有内容类型。

I did it! 我做的!

I think this is not the best way of doing it but it´s working so I am fine until I get a better solution. 我认为这不是最好的方法,但它正在工作,所以我很好,直到我得到一个更好的解决方案。

So I take the Bitmap image and convert it to String: 所以我采用Bitmap图像并将其转换为String:

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
byte[] bitmapByte = outputStream.toByteArray();
String stringEncodedImage = Base64.encodeToString(bitmapByte, Base64.DEFAULT);

Then I create a httpPostRequest and set a JsonObject to it with the image converted to String in it. 然后我创建一个httpPostRequest并为其设置一个JsonObject,并将图像转换为String。

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://my_app_path/_ah/api/registration/v1/uploadImage");

JSONObject jsonObject = new JSONObject();
jsonObject.put("image",stringEncodedImage);

StringEntity stringEntity = new StringEntity(jsonObject.toString());
httpPost.addHeader("Content-Type", "application/json");
httpPost.setEntity(stringEntity);
HttpResponse response = httpClient.execute(httpPost);

On the server side, in my Endpoint, I do this: 在服务器端,在我的端点中,我这样做:

@ApiMethod(name = "uploadImage", httpMethod = "POST")
public JSONObject uploadImage(JSONObject request) throws IOException
{
    String imageInString = (String) request.get("image");
    Blob blob = new Blob(imageInString.getBytes());
    ....save blob and do whatever you want...
}

The same goes the other way. 反过来也是这样。 I pack Blob into JsonObject and send it over. 我将Blob打包到JsonObject中并将其发送出去。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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