Загрузка нескольких изображений с видео на сервер по одному, используя multipart - PullRequest
0 голосов
/ 14 февраля 2020

Привет, сообщество переполнения стека

Я хочу отправить несколько изображений с одним видео на сервер одно за другим. Для этого я написал сервис, который синхронно загружает изображения на сервер по одному. Но здесь у меня возникает проблема, когда я отправляю 20 изображений на сервер, только несколько изображений сохраняются, но я получаю ответ 200 для всех 20 изображений. Предположим, я отправил 20 изображений на сервер, но только 10-12 были сохранены.

Я не понимаю, в чем проблема, это проблема на стороне сервера?

Есть ли кто-нибудь, кто может столкнуться с этой проблемой, кроме меня?

Вот мой код сервисного кода.

 @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, "Service created");

        createNotification();
        IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        networkMonitorReceiver = NetworkMonitorReceiver.getInstance();
        networkMonitorReceiver.setNetworkChangeListener(NetworkMonitoringService.this);
        registerReceiver(networkMonitorReceiver, intentFilter);

    }


    /**
     * When the app's NetworkConnectionActivity is created, it starts this service. This is so that the
     * activity and this service can communicate back and forth. See "setUiCallback()"
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand");

        if (intent != null) {
            docLocation = intent.getStringExtra(ConstantsBundleTags.DOC_LOCATION);
            pickupUniqueNumber = intent.getStringExtra(ConstantsBundleTags.PICKUP_UNIQUE_NUMBER);
            chassisNo = intent.getStringExtra(ConstantsBundleTags.CHASSIS_NO);
        }
        return START_REDELIVER_INTENT;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (networkMonitorReceiver != null) {
            Log.e(TAG, "onDestroy: ");
            unregisterReceiver(networkMonitorReceiver);
            networkMonitorReceiver = null;
        }
    }

    public byte[] getImageFromBitmap(Context context, String imagePath) {

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imagePath, options);
        options.inSampleSize = calculateInSampleSize(options, Math.abs(500), Math.abs(500));
        options.inJustDecodeBounds = false;

        Bitmap bitmap = null;
        bitmap = BitmapFactory.decodeFile(imagePath, options);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, byteArrayOutputStream);

        return byteArrayOutputStream.toByteArray();
    }

    public byte[] convertVideoToByte(Context context, String imagePath) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        try {
            FileInputStream inputStream = new FileInputStream(imagePath);
            ByteBuffer byteBuffer = ByteBuffer.allocate(inputStream.available());
            inputStream.getChannel().read(byteBuffer);
            byteArrayOutputStream.write(byteBuffer.array());
        } catch (IOException e) {
            e.printStackTrace();
        }


        return byteArrayOutputStream.toByteArray();
    }

    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {

       /* final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.

            while ((halfHeight / inSampleSize) >= reqHeight
                    && (halfWidth / inSampleSize) >= reqWidth) {

                inSampleSize *= 2;
            }
        }*/


        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        final float totalPixels = width * height;
        final float totalReqPixelsCap = reqWidth * reqHeight * 2;
        while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
            inSampleSize++;
        }

        return inSampleSize;
    }


    @Override
    public void onResponse(NetworkResponse response) {

        Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
        deleteFiles();
        stopSelf();
    }

    @Override
    public void onErrorResponse(VolleyError error) {
        Toast.makeText(this, "onErrorResponse: " + error.getMessage(), Toast.LENGTH_SHORT).show();
        Log.e(TAG, "onErrorResponse: " + error.getMessage());
       // stopSelf();
    }

    private void deleteFiles() {
        Utility.deleteFolder(NetworkMonitoringService.this, chassisNo);
       // Utility.deleteFolder(NetworkMonitoringService.this, chassisNo);
    }

    private void sendImagesToServer() {

        HashMap<String, String> params = new HashMap<>();
        byteData = new HashMap<>();
        SharedPreferences preferences = getSharedPreferences(Constants.LOGIN_DATA_PREFS, MODE_PRIVATE);
        params.put("docLocation", docLocation);
        params.put("uniqueNo", pickupUniqueNumber);

        params.put("countryCode", Constants.COUNTRY_CODE);
        params.put("companyId", preferences.getString(ConstantsSharedPrefs.PREFS_KEY_COMPANY_ID, ""));
        params.put("loginUserId", preferences.getString(ConstantsSharedPrefs.PREFS_KEY_USER_ID, ""));
        params.put("imageCountByApp", String.valueOf(Utility.getActualFilesCount(this,chassisNo,Constants.MEDIA_TYPE_IMAGES)));



        Log.d("request---", params.toString());
        File dir = Utility.getRootDirectory(NetworkMonitoringService.this, chassisNo);
        listFilesForFolder(dir);
        PhotoMultipartRequest<NetworkResponse> multipartRequest = new PhotoMultipartRequest<NetworkResponse>
                (
                        Request.Method.POST,
                        this.getResources().getString(R.string.api_url_main) + "Workshop/SavePickupImage", params, byteData, NetworkResponse.class,
                        this, this);
        RequestQueue requestQueue = Volley.newRequestQueue(NetworkMonitoringService.this);


        requestQueue.add(multipartRequest);
        requestQueue.getCache().clear();
    }

    //todo rb
    public void listFilesForFolder(final File folder) {

        for (final File fileEntry : folder.listFiles()) {
            if (fileEntry.isDirectory()) {
                listFilesForFolder(fileEntry);
            } else {
                System.out.println(fileEntry.getName());
                String filename = fileEntry.getAbsolutePath();
                if (filename.contains(".mp4")) {
                    PhotoMultipartRequest.DataPart dataPart = new PhotoMultipartRequest.DataPart(filename,
                            "video/mp4", convertVideoToByte(NetworkMonitoringService.this, filename));
                    byteData.put("video" , dataPart);

                } else {
                    PhotoMultipartRequest.DataPart dataPart = new PhotoMultipartRequest.DataPart(filename,
                            "image/jpg", getImageFromBitmap(NetworkMonitoringService.this, filename));
                    byteData.put("image" , dataPart);
                }
            }
        }
    }

    private void createNotification() {
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("NetworkState", "Network State", NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(channel);
        }
        notification = new NotificationCompat.Builder(NetworkMonitoringService.this, "NetworkState")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentText(getResources().getText(R.string.app_name))
                .setContentTitle(getResources().getText(R.string.app_name))
                .setWhen(System.currentTimeMillis())
                .setPriority(Notification.PRIORITY_HIGH)
                .setLights(Color.parseColor("#B71C1C"), 1000, 6000)
                .build();


        startForeground(NOTIFICATION_ID, notification);
    }


    @Override
    public void OnNetworkChange(boolean isConnect) {
        if (isConnect) {
            Toast.makeText(NetworkMonitoringService.this, "Connected", Toast.LENGTH_SHORT).show();
            startForeground(NOTIFICATION_ID, notification);
            sendImagesToServer();
        } else {
            Toast.makeText(NetworkMonitoringService.this, "Disconnected", Toast.LENGTH_SHORT).show();
            stopForeground(true);
        }
    }


}

- 1. Мой сервис работает нормально. - 2. Проблема в том, что я загружаю 10 файлов, но сохранил только 3 или 4.

...