2017-04-11 135 views
1

Ionic本機提供了文件選擇器和文件插件。 File插件需要文件的絕對路徑才能讀取,但沒有辦法提取這個文件。Ionic2:將文件選擇器URI轉換爲文件路徑

爲了選擇文件,我使用了File Chooser,它返回一個URI。

import { FileChooser } from '@ionic-native/file-chooser'; 

constructor(private fileChooser: FileChooser) { } 

... 

this.fileChooser.open() 
    .then(uri => console.log(uri)) 
    .catch(e => console.log(e)); 

的URI看起來像這樣

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

文件插件可以利用路徑讀取文件。

import { File } from '@ionic-native/file'; 

constructor(private file: File) { } 

... 

this.file.readAsText(this.file.dataDirectory, 'myFile') 
.then((content) => 
     console.log(this.file.dataDirectory + 'myFile'); 
     console.log(content) 
).catch(err => 
     console.log('File doesnt exist') 
); 

該路徑如下所示。

file:///data/data/com.myapp.myappmobile/files/myFile 

如何使用這兩個組件。使用FileChooser挑選文件,然後在Ionic 2中讀取它。

回答

4

請安裝FilePath插件以獲取本機路徑。 然後使用下面的代碼。 舉例說,你正在選擇一個圖像文件。

nativepath: any; 
uploadfn(){ 
    this.fileChooser.open().then((url) => { 
    (<any>window).FilePath.resolveNativePath(url, (result) => { 
    this.nativepath = result; 
    this.readimage(); 
    } 
) 
}) 
} 

readimage() { 
    (<any>window).resolveLocalFileSystemURL(this.nativepath, (res) => { 
     res.file((resFile) => { 
     var reader = new FileReader(); 
     reader.readAsArrayBuffer(resFile); 
     reader.onloadend = (evt: any) => { 
      var imgBlob = new Blob([evt.target.result], { type: 'image/jpeg'}); 
      //do what you want to do with the file 
     } 
     }) 
    }) 
    } 

請在這裏看一看 - http://tphangout.com/ionic-2-serving-images-with-firebase-storage/

(涉及如何選擇從手機的文件系統的圖像,並把它上傳到火力存儲)

希望這有助於你。謝謝。

+1

它的工作。我想知道!爲什麼文件選擇器會返回一個uri。在哪裏使用uri? –

+2

只有Android支持FilePath,如何解決IOS上的filePath? – noor

0

使用文件路徑:

import { File } from '@ionic-native/file'; 
import { FileChooser } from '@ionic-native/file-chooser'; 

constructor(
    private fileChooser: FileChooser, 
    private filePath: FilePath 
) { 

} 

private captureFile(): Promise<any> { 
     return new Promise((resolve, reject) => { 
      this.fileChooser.open().then((uri) => { 

       this.filePath.resolveNativePath(uri) 
        .then((filePath) => { 
         alert(filePath)      
        }, (err) => { 
         reject(err); 
        }) 
      }, (err) => { 
       reject(err); 
      }); 

     }); 

    }