image - 从 dataDirectory 文件路径设置为 img 的 src

标签 image typescript ionic2 cordova-plugins

我正在尝试设置 src<img>在来自文件字符串路径的 html 上。

路径取自cordova.file.dataDirectory Ionic2 上的 cordova 插件( Typescript ) 看起来像:

编辑以显示我的代码:

这是profile.ts代码的相关部分

...
import {Camera} from "ionic-native";
...
import {API} from "../../services/api";
import {ImageAdquistionService} from "../../services/imageAdquisition.service";
...
import {Network,File} from 'ionic-native';




declare let cordova: any;


@Component({
  selector:    'page-profile',
  templateUrl: 'profile.html'
})

export class ProfilePage implements OnInit{


  connected:boolean = false;

  imagePath: string = "./assets/img/pio.jpg";
  userInfo: User = new User();


  constructor(

              private api:API,
              private imageAdquistionService: ImageAdquistionService,
              ){

    //seleted tab by default
    this.tabs="info";

    this.connected = Network.type !== "none";

  }

  ngOnInit(): void {

    this.localStorageService.getUserInfo().then(user => {
      this.userInfo = user;
      if (this.userInfo.imagenPerfil !== "defAlert") {

        File.checkFile(cordova.file.dataDirectory,this.userInfo.profileImage).then(result => {
         console.log("exist")
          this.imagePath = cordova.file.dataDirectory + this.userInfo.profileImage;
         })
         .catch(error => {
         console.log("not exist " + JSON.stringify(error))
         })
      }
    });

  }

  presentImageOptions(){

    let actionSheet = this.actionSheetCtrl.create({
      title: 'Select an option',
      buttons: [
        {
          icon: 'camera',
          text: 'photo',
          handler: () => {

            let navTransition = actionSheet.dismiss();
            navTransition.then(() => {
              this.imageAdquistionService.getANewImage(Camera.PictureSourceType.CAMERA).then(imageData => {
                if(imageData.success){
                  this.uploadImage(imageData.fileName, imageData.filePath);
                }
                else{this.presentToast(imageData.message)}
              })
            });
            return false;
          }
        }, {
          icon: 'image',
          text: 'Gallery',
          handler: () => {

            let navTransition = actionSheet.dismiss();
            navTransition.then(() => {
              this.imageAdquistionService.getANewImage(Camera.PictureSourceType.PHOTOLIBRARY).then(imageData => {
                if(imageData.success){
                  this.uploadImage(imageData.fileName, imageData.filePath);
                }
                else{this.presentToast(imageData.message)}
              });
            });
            return false;
          }
        }, {
          text: 'Close',
          role: 'cancel',
          handler: () => {
            console.log('Cancel clicked');
          }
        }
      ]
    });
    actionSheet.present();
  }


  uploadImage(fileName: string, filePath: string){


    this.presentLoadingCustom();
    this.localStorageService.getAccessToken().then(token  => {

      this.api.uploadFile(fileName,filePath).then(result =>{
        this.loading.dismissAll();
        console.log("uploaded OK);

        this.userInfo.profileImage = fileName;
        this.imagePath = filePath;

          this.api.updateUserPreferences(this.userInfo,token).then(result =>{
            if(result.success) {
              console.log("updated ok");

              this.presentToast("image updated succesfully");
            }
          });

      })
        .catch(error => {
          this.presentToast(error.message)
        })
    })

  }

}

这是imageAdquisitionService的相关代码

import { Injectable } from '@angular/core';
import {LocalStorageService} from "./localStorage.service";
import {Platform} from "ionic-angular";
import {Camera, File, FilePath} from "ionic-native";
import {API} from "./api";


declare let cordova: any;

@Injectable()
export class ImageAdquistionService {


  constructor(private storage: LocalStorageService,
              public platform: Platform,
              private api:API) {
  }


  getANewImage(src):Promise<any>{
    let options = {
      quality: 60,
      sourceType: src,
      saveToPhotoAlbum: false,
      correctOrientation: true
    };


    return Camera.getPicture(options).then((imageData) => {

      // Special handling for Android library
      if (this.platform.is('android') && src === Camera.PictureSourceType.PHOTOLIBRARY) {


        return FilePath.resolveNativePath(imageData)
          .then(filePath => {

              let correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
              let currentName = imageData.substring(imageData.lastIndexOf('/') + 1, imageData.lastIndexOf('?'));

                return this.storage.getUserInfo().then(user => {

                    return this.copyFileToLocalDir(correctPath, currentName, this.createFileName(user._id)).then(copyResult => copyResult);


            });

            }, (error) => {
              // Handle error
              return {success: false, message: error.message};
            }
          );
      } else {

        let currentName = imageData.substr(imageData.lastIndexOf('/') + 1);
        let correctPath = imageData.substr(0, imageData.lastIndexOf('/') + 1);

        return this.storage.getUserInfo().then(user => {

            return this.copyFileToLocalDir(correctPath, currentName, this.createFileName(user._id)).then(copyResult => copyResult);

        });
      }
    }, (error) => {
        // Handle error
        return {success: false, message: error.message};
      }
    )
  }
  // Create a new name for the image
  createFileName(id:string) {
    let d = new Date(),
      n = d.getTime(),
      newFileName =  n + ".jpg";

      newFileName = id + "_" + newFileName;
      return newFileName;


  }

// Copy the image to a local folder
  copyFileToLocalDir(namePath, currentName, newFileName):Promise<any> {

    return File.copyFile(namePath, currentName, cordova.file.dataDirectory, newFileName).then(success => {

      console.log("response of copy " + JSON.stringify(success));
      return {success: true, fileName: newFileName, filePath: this.pathForImage(newFileName)};

    }, error => {
      this.api.logIonicView("Error while storing file " + error.message);

      return {success: false, message: error.message};
    });
  }

  // Always get the accurate path to the apps folder
  public pathForImage(img) {
    if (img === null) {
      return '';
    } else {
      return cordova.file.dataDirectory + img;
    }
  }

}

这是api服务的相关代码

uploadFile(name:string, path:string):Promise<any>{

    let options = {
      fileKey: "file",
      fileName: name,
      chunkedMode: false,
      mimeType: "multipart/form-data",
      params : {'fileName': name}
    };

    let fileTransfer = new Transfer();

    // Use the FileTransfer to upload the image

    return fileTransfer.upload(path, this.urlBase + "upload", options)
      .then(data => {
        console.log("message on filetransfer "+ JSON.stringify(data.response));

        data})
      .catch(this.handleError);

  }

这是html代码的相关代码

<ion-item no-lines class="item-bar-profile">
      <ion-avatar>
        <img class="centered" src="imagePath" (click)="presentOptions();">
      </ion-avatar>
</ion-item>

这是一个默认图像路径硬类型化的示例:

this.imagepath = "./assets/img/pio.jpg"

enter image description here

这是一个以编程方式将路径更改为

的示例

this.imagepath = file:///data/user/0/com.ionicframework.myionicproject494629/files/58db7e92be26f32d4c8c01d2_1491989021049.jpg

enter image description here

谢谢

最佳答案

我遇到了同样的问题。我意识到虽然我在 android 设备上运行,但我是在 ionic 中实时运行它,它不适用于 cordova 插件。因此,我没有执行ionic cordova run android -l -c,而是运行命令ionic cordova run android

关于image - 从 dataDirectory 文件路径设置为 img 的 src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43363480/

相关文章:

android - 从 android 相机拍照并将其发送到网络服务器

javascript - 不要滚动元素调整大小

javascript - typescript - 字符串字面量类型到类型字符串

angular - Ionic 2 在应用程序启动后重定向到另一个页面

cordova - 使用 angular2 - ionic 2 下载文件

angular - 如何加快选择框的性能?

css - 优化图像/CSS 以提高速度性能

html - CSS 图像 :hover based on alt value

Angular2 路由器 : Error: Cannot find primary outlet to load 'InboxComponent'

html - Firefox 不显示来自缓存的图像仅替代文本