選擇圖庫中的文件上傳請看另外一文章
在移動項目開發中,使用的是Ionic框架,當中涉及到文件上傳。javascript
開發思路:java
開發流程涉及到的組件有(Ionic官方文檔)shell
下面只列舉文件選擇
的插件安裝方法。文件打開
和文件路徑
安裝方式同理,文檔有具體描述,文件選擇
插件有版本的注意事項npm
Ionic3.x框架
$ ionic cordova plugin add cordova-plugin-filechooser $ npm install --save @ionic-native/file-chooser@4
Ionic4.xionic
$ ionic cordova plugin add cordova-plugin-filechooser $ npm install @ionic-native/file-chooser
文件選擇
filechooser插件能調用手機中的文件管理,選擇文件夾裏面的文件,成功則返回文件的路徑。
使用方法以下this
Ionic3.xurl
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'}); // 對圖片操做的 業務代碼 } }) }) }