ionic3 调取相册并上传图片

2018-05-28  本文已影响0人  南京确善能

调取相册

ionic cordova plugin add cordova-plugin-telerik-imagepicker --variable PHOTO_LIBRARY_USAGE_DESCRIPTION="your usage message"
npm install --save @ionic-native/image-picker

your message 是一个说明

 /**
   * 选择图片
   */
  imagePicker(){
    this.imgPicker.imgPicker().then(result=>{
      this.fileTransfer.upload(result[0],AppApi.api_pic_upload_native).then(data=>{ //这里是上传图片的回调
     console.log(data);
      })
    })
  }

ImagePickerProvider

import { ImagePicker } from '@ionic-native/image-picker';
import { ImagePickerOptions } from '@ionic-native/image-picker';

/**
 * 调取相册
 */
@Injectable()
export class ImagePickerProvider {
  
  constructor(public http: HttpClient,private imagePicker: ImagePicker) {
     //获取权限
    this.imagePicker.hasReadPermission().then(result=>{
      if(!result){
          this.imagePicker.requestReadPermission().then(result=>{
            console.log("读取权限:"+result)
          })
      }
    })
  }

  /**
   * 调取相册 获取图片
   */
  imgPicker():Promise<any>{
      const options : ImagePickerOptions={maximumImagesCount:1};//只选择一张图片
      return new Promise((resolve, reject) => {
        this.imagePicker.getPictures(options).then((results) => {
          resolve(results);
        }, (err) => { 
          reject(err)
        });
      });
  }
}

上传文件

ionic cordova plugin add cordova-plugin-file-transfer
npm install --save @ionic-native/file-transfer

FileTransferProvider

import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer';

import { AppApi,AppConfig } from '../../app/config';
/**
 * native操作文件
 */
@Injectable()
export class FileTransferProvider {

  constructor(public http: HttpClient,private transfer: FileTransferObject,private appCfg: AppConfig) {
  }

   /**
    * 上传文件
    * @param imgPath 文件路径
    * @param serverUrl 接口地址 
    */
  upload(imgPath,serverUrl):Promise<any>{
    let options: FileUploadOptions = {
       fileKey: 'pic',//表单name
       fileName: imgPath.substring(imgPath.lastIndexOf("/")+1,imgPath.length),
       httpMethod:'post',
       params:{}//自定义的参数
    }
    return new Promise((resolve, reject) => {
      this.transfer.upload(imgPath, serverUrl, options)
      .then((data) => {
        resolve(JSON.parse(data['response']));//这里返回的是没有处理的过的
      }, (err) => {
        reject(err)
      })
    });
   
  }
}

闪退问题

cordova plugin add cordova-android-support-gradle-release  --variable ANDROID_SUPPORT_VERSION=26.+
上一篇下一篇

猜你喜欢

热点阅读