安装插件

安装插件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) =&gt; {
            for (const res of results) {
                this.upload(res);
            }
        }, (err) =&gt; {
        });
    }

    // 上传文件
    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) =&gt; {
                alert('success');
            })
            .catch((e) =&gt; {
            });
    }

}

最终效果

> 作者:垚淼
> 出处:www.ljmin.com

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!