Ionic34文件选择插件filechooser选择图片上传的问题

9次阅读

共计 1973 个字符,预计需要花费 5 分钟才能阅读完成。

抉择图库中的文件上传请看另一文章

在挪动我的项目开发中,应用的是 Ionic 框架,当中波及到文件上传。

开发思路:

  1. 应用文件抉择插件获取门路
  2. 应用门路上传文件

开发流程波及到的组件有(Ionic 官网文档)

  • 文件抉择 https://ionicframework.com/do…
  • 文件关上 https://ionicframework.com/do…(在已上传的文件列表中可能你会应用上)
  • 文件门路 https://ionicframework.com/do…

插件装置

上面只列举 文件抉择 的插件装置办法。文件关上 文件门路 装置形式同理,文档有具体形容,文件抉择 插件有版本的注意事项

Ionic3.x

$ ionic cordova plugin add cordova-plugin-filechooser
$ npm install --save @ionic-native/file-chooser@4

Ionic4.x

$ ionic cordova plugin add cordova-plugin-filechooser
$ npm install @ionic-native/file-chooser

文件抉择 filechooser

文件抉择 filechooser 插件能调用手机中的文件治理,抉择文件夹外面的文件,胜利则返回文件的门路。
应用办法如下

Ionic3.x

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

constructor(private fileChooser: FileChooser) { }

...
this.fileChooser.open()
  .then(uri => {
      // uri 文件的门路
      console.log(uri)
  })
  .catch(e => console.log(e));

Ionic4.x

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

constructor(private fileChooser: FileChooser) { }

...
this.fileChooser.open()
  .then(uri => {
      // uri 文件的门路
      console.log(uri)
  })
  .catch(e => console.log(e));

这时候,你能够应用取得的 uri,联合 http 申请 或者 file-transfer 插件进行文件上传。
然而,你在抉择图片文件进行上传时,发现会上传失败,具体调试时发现并没上进行文件上传,其实起因是没有找到文件。请持续往下看。

获取文件的理论门路

须要装置插件filePath 文件门路 获取图片文件的理论门路

this.fileChooser.open().then(uri => {
        // uri 文件的门路

        // 你会发现通过此插件,抉择图片文件跟抉择其余文件(.doc/.xlsx/.docx/.ppt ...),取得的 uri 是有区别的
        // 图片文件门路:content://media/....
        // 其余文件门路:file:///storage/....

        // 因而将图片文件转换成理论门路,或者叫绝对路径
        (<any>window).FilePath.resolveNativePath(uri, (result) => {this.util.tip(result);
          // 调用文件上传(此办法须要自行编写)
          this.uploadAttachment(result);
        });
      })
      .catch(e => console.log(e));

这时,就能失常上传附件了。

读取抉择的图片

有时候你须要方才抉择好的图片,进行下一步的操作。
你能够参考上面的写法

upload(){this.fileChooser.open().then((url) => {(<any>window).FilePath.resolveNativePath(url, (result) => {
        // 上传文件
        this.uploadFileByPath(filePath);
        // 读取图片
        this.readimage(filePath);
      })
    })
}

uploadFileByPath(filePath){// 实现上传的代码}

readimage(filePath) {(<any>window).resolveLocalFileSystemURL(filePath, (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'});
          // 对图片操作的 业务代码
        }
      })
    })
  }
正文完
 0