时间:2021-03-04 13:50:15 | 栏目:AngularJS | 点击:次
前言
ionic是一个垮平台开发框架,可通过web技术开发出多平台的应用。但只建议开发简单应用。复杂的应用需要用到许多cordova插件,而cordova插件的更新或者移动平台的更新很可能导致插件的不可用,维护升级成本较高。
安装插件
安装插件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) => { }); } }
最终效果
总结