Плагин IONIC камеры FILE_URI, возвращающий другой формат пути к файлу в зависимости от выбранного типа файла (видео / изображение) - PullRequest
0 голосов
/ 27 октября 2019

У меня проблема с тем, что возвращаемый uri имеет формат:

"content: //com.android.providers.media.documents/document/image%3A18112"

вместо:

"/ хранилище данных / эмуляция / 0 / Анимированные GIF-файлы WhatsApp / Media / WhatsApp / VID-20191026-WA0003.mp4"

Это кажется проблемой только при выборе изображения из галереи. С видеофайлами это правильный формат. моя версия для плагина:

"@ ionic-native / camera": "^ 5.15.1"

"cordova-plugin-camera": "^ 4.1.0"

Какие последние версии, насколько я знаю. Я тестирую на Samsung Galaxy S8.

Мой код указан ниже:

import { Injectable } from '@angular/core';
import { CameraOptions, Camera, MediaType } from '@ionic-native/camera/ngx';
import { CameraProviderResponse } from '../objects/cameraProviderResponse';

@Injectable()
export class CameraProvider {

    constructor(public camera: Camera) {

    }

    openCamera(selectedMediaType: MediaType, allowedMediaType: MediaType): Promise<CameraProviderResponse> {
        const options: CameraOptions = {
            sourceType: this.camera.PictureSourceType.SAVEDPHOTOALBUM,
            destinationType: this.camera.DestinationType.FILE_URI,
            mediaType: selectedMediaType
        };
        return this.camera.getPicture(options).then((mediaPath) => {
            let re = /(?:\.([^.]+))?$/;
            let fileExtension = re.exec(mediaPath)[0];
            let mediaType;
            if (fileExtension === '.jpeg' || fileExtension === '.jpg' || fileExtension === '.png' || fileExtension === '.gif' && (allowedMediaType === MediaType.ALLMEDIA || allowedMediaType === MediaType.PICTURE)) {
                mediaType = MediaType.PICTURE;
            }
            else if (fileExtension === '.mp4' && (allowedMediaType === MediaType.ALLMEDIA || allowedMediaType === MediaType.PICTURE)) {
                mediaType = MediaType.VIDEO;
            }
            else {
                return this.openCameraFailed();
            }
            return {
                success: true,
                mediaPath: mediaPath,
                mediaType: mediaType,
                fileExtension: fileExtension

            };
        }, error => {
            return this.openCameraFailed();
        }).catch(error => {
            console.log(error);
            return this.openCameraFailed();
        });
    }

    openCameraFailed(): CameraProviderResponse {
        return {
            success: false
        };
    }
}

Если вам нужна дополнительная информация. Пожалуйста, спросите.

1 Ответ

0 голосов
/ 27 октября 2019

В настоящее время я исправил это следующим образом:

import { Injectable } from '@angular/core';
import { CameraOptions, Camera, MediaType } from '@ionic-native/camera/ngx';
import { CameraProviderResponse } from '../objects/cameraProviderResponse';
import { FilePath } from '@ionic-native/file-path/ngx';
//bug: temp fix stack overflow post: /13186961/plagin-ionic-kamery-fileuri-vozvraschayschii-drugoi-format-failu-zavisimosti-vybrannogo-faila-video-izobrazheniecomment103477183_58581038
@Injectable()
export class CameraProvider {

  constructor(public camera: Camera, public filePath: FilePath) {

  }

  openCamera(selectedMediaType: MediaType, allowedMediaType: MediaType): Promise<CameraProviderResponse> {
    const options: CameraOptions = {
      sourceType: this.camera.PictureSourceType.SAVEDPHOTOALBUM,
      destinationType: this.camera.DestinationType.FILE_URI,
      mediaType: selectedMediaType
    };
    return this.camera.getPicture(options).then((mediaPath) => {      
      let fileExtension = this.getFileExtension(mediaPath);
      if(this.getMediaType(fileExtension) === null) {
        return this.filePath.resolveNativePath(mediaPath)
        .then(path => {
          return this.getCameraProviderResponse(allowedMediaType, path);
        })
        .catch(err => {
          console.log(err);
          return this.openCameraFailed();          
        });
      }
      else {
        return this.getCameraProviderResponse(allowedMediaType, mediaPath);
      }
    }, error => {
      return this.openCameraFailed();
    }).catch(error => {
      console.log(error);
      return this.openCameraFailed();
    });
  }

  getCameraProviderResponse(allowedMediaType: MediaType, path:string) {
    let fileExtension = this.getFileExtension(path);
    let mediaType = this.getMediaType(fileExtension);
     if(mediaType === null) {
       return this.openCameraFailed();
     }
      return {
        success: true,
        mediaPath: path,
        mediaType: mediaType,
        fileExtension: fileExtension

      };
  }

  //fix for android
  getFileExtension(path: string) {
    let re = /(?:\.([^.]+))?$/;
    return re.exec(path)[0];
  }
  //fix for android
  getMediaType(fileExtension: string) {
    if (fileExtension === '.jpeg' || fileExtension === '.jpg' || fileExtension === '.png' || fileExtension === '.gif') {
      return MediaType.PICTURE;
    }
    else if (fileExtension === '.mp4') {
      return MediaType.VIDEO;
    }
    else return null;
  }

  openCameraFailed(): CameraProviderResponse {
    return {
      success: false
    };
  }
}

Это кажется немного хакерским, но пока работает. Купите мне немного времени, чтобы поближе взглянуть на проблему. Если я найду лучшее решение, я также опубликую его здесь! В это время. Если кто-то еще найдет лучшее решение этой проблемы, пожалуйста, опубликуйте его здесь!

...