安裝插件 安裝插件Image Picker $ ionic cordova plugin add cordova plugin telerik imagepicker $ npm install @ionic native/image picker 安裝插件File Transfer $ ionic ...
安裝插件
安裝插件Image Picker
$ ionic cordova plugin add cordova-plugin-telerik-imagepicker
$ npm install @ionic-native/image-picker
安裝插件File Transfer
$ ionic cordova plugin add cordova-plugin-file-transfer
$ npm install @ionic-native/file-transfer
添加到app.module.ts
import { ImagePicker } from '@ionic-native/image-picker/ngx';
import { FileTransfer} from '@ionic-native/file-transfer/ngx';
html添加控制項
<ion-button (click)="chooseImage()">上傳圖片</ion-button>
編輯ts文件
export class UploadPage {
constructor(
private imagePicker: ImagePicker,
private transfer: FileTransfer
) {
}
// 選擇圖片,選擇完成立即上傳
chooseImage() {
const options = {
maximumImagesCount: 1
// width: int,
// height: int,
// quality: int (0-100),
// outputType: int
};
this.imagePicker.getPictures(options).then((results) => {
for (const res of results) {
this.upload(res);
}
}, (err) => {
});
}
// 上傳文件
upload(file) {
const fileTransfer: FileTransferObject = this.transfer.create();
const options: FileUploadOptions = {
fileKey: 'file',
fileName: timestamp() + '.jpg',
params: {
type: 'file',
action: 'upload',
timestamp: timestamp(),
auth_token: '79e1bd1504962034c068461d58b9cd89a1d8a4a1'
},
headers: {}
};
fileTransfer.upload(file, 'https://imgbb.com', options)
.then((data) => {
alert('success');
})
.catch((e) => {
});
}
}
最終效果
> 作者:垚淼
> 出處:www.ljmin.com