首页 文章

Ionic2:将文件选择器uri转换为文件路径

提问于
浏览
2

Ionic native分别提供File Chooser和File插件 . File插件需要读取文件的绝对路径,但无法选择文件 .

为了选择文件,我使用了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中读取它 .

2 回答

  • 6

    请安装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/

    (如何从手机的文件系统中选择图像并将其上传到firebase存储中)

    希望这能帮到你 . 谢谢 .

  • 0

    使用FilePath:

    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);
                });
    
            });
    
        }
    

相关问题