2017-04-12 55 views
1

我試圖在文件的字符串路徑的html上設置<img>src從dataDirectory文件路徑設置爲img的src

的路徑是從cordova.file.dataDirectory科爾多瓦插件上Ionic2Typescript)獲得,並且看起來像:

EDIT顯示我的CODE:

這是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 =:與hardtyped文件:///data/user/0/com.ionicframework.myionicproject494629/files/58db7e92be26f32d4c8c01d2_1491989021049.jpg

enter image description here

謝謝

回答

0

這是錯誤的[src]="this.imagepath"。無需使用this這裏。

您可以嘗試如下所示。

file.html

[src]="imagepath" 
+0

你是對的,這是一個類型錯誤。我已經用圖像路徑和更多信息的示例更新了原始帖子。當我以編程方式將默認圖像更改爲新路徑時,它呈現爲透明 – Hanzo

+0

您只需在此處做一件簡單的事情即可。請參閱此URL的哪個部分將生成所需的圖像('file:/// data/user/0/com.ionicframework.myionicproject494629/files/58db7e92be26f32d4c8c01d2_1491989021049.jpg')。據此,只是做字符串操作,並讓你的工作網址。 – Sampath

0

你並不需要使用this[src]="this.imagepath"

我覺得

[src]="imagepath" 

src={{imagepath}} 

會工作得很好。

備註:如果file:///usr...package....image.jpg是有效的路徑,則可以使用。

+0

你是對的,這是一個類型錯誤。我已經用圖像路徑和更多信息的示例更新了原始帖子。當我以編程方式將默認圖像更改爲新路徑時,它將呈現爲透明 – Hanzo

+0

無論您的路徑是,請嘗試使用''如果呈現,則它是有效的圖像路徑。它不會。 –

+0

我試圖硬編碼的路徑,仍然不顯示。File.checkFile返回該文件存在。將是任何影響,是一個離子頭像? – Hanzo

1

我有這個相同的問題。我意識到,儘管我在Android設備上運行,但是我使用離子形式運行它,但它不適用於cordova插件。因此,我不得不使用ionic cordova run android -l -c作爲ionic cordova android