Как написать медпункт postRequest для получения img назад и показа в ImageView - PullRequest
0 голосов
/ 20 октября 2019

Этот код для подключения сервера (фляги) к нему подключен! отправьте имя img android_flask и строку ответа «Ответ сервера: завершено», так что если * я хочу, чтобы ответ показал Img from dir (flask.Have код) и показал его в ImageView, как выполнить ?? *

    public void connectServer(View v) {
                TextView responseText = findViewById(R.id.responseText);
                if (imagesSelected == false) { // This means no image is selected and thus nothing to upload.
                    responseText.setText("No Image Selected to Upload. Select Image(s) and Try Again.");
                    return;
                }
                responseText.setText("Sending the Files. Please Wait ...");

                //EditText ipv4AddressView = findViewById(R.id.IPAddress);
                String ipv4Address = "192.168.1.20";
                //EditText portNumberView = findViewById(R.id.portNumber);
                String portNumber = "8888";

                Matcher matcher = IP_ADDRESS.matcher(ipv4Address);
                if (!matcher.matches()) {
                    responseText.setText("Invalid IPv4 Address. Please Check Your Inputs.");
                    return;
                }

                String postUrl = "http://" + ipv4Address + ":" + portNumber + "/";

                MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);

                for (int i = 0; i < selectedImagesPaths.size(); i++) {
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inPreferredConfig = Bitmap.Config.RGB_565;

                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    try {
                        // Read BitMap by file path.
                        Bitmap bitmap = BitmapFactory.decodeFile(selectedImagesPaths.get(i), options);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                    }catch(Exception e){
                        responseText.setText("Please Make Sure the Selected File is an Image.");
                        return;
                    }
                    byte[] byteArray = stream.toByteArray();

                    multipartBodyBuilder.addFormDataPart("image" + i, "Android_Flask_" + i + ".jpg", RequestBody.create(MediaType.parse("image/*jpg"), byteArray));
                }

                RequestBody postBodyImage = multipartBodyBuilder.build();

        //        RequestBody postBodyImage = new MultipartBody.Builder()
        //                .setType(MultipartBody.FORM)
        //                .addFormDataPart("image", "androidFlask.jpg", RequestBody.create(MediaType.parse("image/*jpg"), byteArray))
        //                .build();

                postRequest(postUrl, postBodyImage);
            }

И вызов postRequest Я не знаю, что-то в этом коде нужно изменить или добавить для вызова medthod в колбе.

void postRequest(String postUrl, RequestBody postBody) {

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(postUrl)
                .post(postBody)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // Cancel the post on failure.
                call.cancel();
                Log.d("FAIL", e.getMessage());

                // In order to access the TextView inside the UI thread, the code is executed inside runOnUiThread()
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        TextView responseText = findViewById(R.id.responseText);
                        responseText.setText("Failed to Connect to Server. Please Try Again.");
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                // In order to access the TextView inside the UI thread, the code is executed inside runOnUiThread()
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        TextView responseText = findViewById(R.id.responseText);
                        try {
                            responseText.setText("Server's Response\n" + response.body().string());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
    }

А вот код в колбедля отправки img из реж.

@app.route('/get_image')
def get_image():
    path = r'C:\Users\User\Desktop\AndroidFlask-master\Part 1\FlaskServer\download'
    return send_file(os.path.join(path,newest()), mimetype='image/gif')
...