Ionic—图片上传组件开发

版权声明:作者已开启版权声明,如转载请注明转载地址。 https://blog.csdn.net/qq_34829447/article/details/84981616

一.修改头像功能页面的整体结构讲解

1.安装必要的组件

使用原生的功能时将采用ionic native

  • 安装四个插件

    npm install --save @ionic-native/camera @ionic-native/file @ionic-native/file-path @ionic-native/transfer
    #camera用于相机
    #file用于访问本地相册
    #file-path用于文件路径相关处理
    #transfer用于传输相关文件
    
  • 使用ionic cordova添加插件【cordova主要用于android和ios底层通讯】

    sudo ionic cordova plugin add cordova-plugin-camera --save
    sudo ionic cordova plugin add cordova-plugin-file --save
    sudo ionic cordova plugin add cordova-plugin-file-transfer --save
    sudo ionic cordova plugin add cordova-plugin-filepath --save
    
  • 全局Provider中导入File,Transfer,FilePath,Camera

二.修改头像功能页面的布局开发

1.功能设计

  • 创建上传头像页面ionic g page headface
  • 将上传头像页面在全局app.modules文件中定义
  • 在user文件中的头像添加跳转headface页面(使用navController)
  • 编辑headface页面内容

2.实例代码

  • user.html添加内容

    <button ion-item (click)="uploadUserAvatar()">
        <ion-avatar item-start>
            <img [src]="avatarUrl">
        </ion-avatar>
        <h2>
            Edit user avatar
        </h2>
    </button>
    
  • user.ts添加内容

    //upload user avatar
    uploadUserAvatar() {
        this.navCtrl.push(HeadfacePage);
    }
    
  • headface.html添加内容

    <ion-header>
      <ion-navbar>
        <ion-title>Upload Avatar</ion-title>
      </ion-navbar>
    </ion-header>
    
    <ion-content padding>
      <img src="{{pathForImage(lastImage)}}" style="width:100%" [hidden]="lastImage === null">
      <h3 [hidden]="lastImage !== null">Please select a picture from photo library</h3>
    </ion-content>
    
    <ion-footer>
      <ion-toolbar color="primary">
        <ion-buttons>
          <button ion-button icon-left (click)="presentActionSheet()">
            <ion-icon name="camera"></ion-icon>选择...
          </button>
          <button ion-button icon-left (click)="uploadImage()" [disabled]="lastImage === null">
            <ion-icon name="cloud-upload"></ion-icon>上传
          </button>
        </ion-buttons>
      </ion-toolbar>
    </ion-footer>
    

三.获取图片的逻辑处理

1.开发思路

  • 用户ID的获取
  • 显示选择图片的方式
  • 共用获取图片的方法处理

2.功能设计

  • 给“选择…”的button添加监听事件用于开启ActionSheet【ActionSheetController组件】

    //部分代码
    viewActionSheet() {
        let action = this.actionSheetCtrl.create({
          title:'Select Picture',
          buttons:[
            {
              text:'Select From Photo Library',
              handler:()=>{
    			//选择本地图片逻辑
                this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
              }
            },
            {
              text:'Use Camera',
              handler:()=>{
    			//使用相机拍照逻辑
                this.takePicture(this.camera.PictureSourceType.CAMERA);
              }
            },
            {
              text:'Cancel',
              role:'cancel'//关闭actionSheet逻辑
            }
          ]
        });
        action.present();
      }
    
  • 定义用户属性:userId,errorMessage,lastImage(最后一个用户选择的图片的位置),注入相关Controller

  • 添加ionViewDidEnter函数从storage中获取用户Id用于之后访问后台API

  • 导入之前安装的插件,并添加对应的构造参数

    //导入之前安装的组件
    import {File} from '@ionic-native/file';
    import {Transfer,TransferObject} from '@ionic-native/transfer';
    import {FilePath} from '@ionic-native/file-path';
    import {Camera} from '@ionic-native/camera';
    
  • 导入第三方的库到TS项目中

    declare var cordova:any;
    
  • 添加拍照调用的函数

    //照相的函数
    takePicture(sourceType){
        //定义相机的一些参数
        let options = {
            quality:100,//定义图片质量
            sourceType:sourceType,
            saveToPhotoAlbum:false,//是否把拍摄的照片存到相册中去
            correctOrientation:true//是否纠正拍摄照片的方向
        };
        //获取图片的方法
        this.camera.getPicture(options).then((imagePath)=>{
            //特别处理android平台的文件路径问题
            if(this.platform.is('android') && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY){//通过platform判断是什么平台,Platform也同样需要导入
                //获取android平台下的真实路径
                this.filePath.resolveNativePath(imagePath).then(filePath=>{
                    //获取正确的路径
                    let correctPath = filePath.substr(0,filePath.lastIndexOf('/')+1);
                    //获取正确的文件名
                    let correntName = imagePath.substring(imagePath.lastIndexOf('/')+1,imagePath.lastIndexOf('?'));
                    this.copyFileToLocalDir(correctPath,correntName,this.createFileName())
                });
            }
            else{//其他平台的处理
                //获取正确的路径
                let correctPath = imagePath.substr(0,imagePath.lastIndexOf('/')+1);
                //获取正确的文件名
                let correntName = imagePath.substring(imagePath.lastIndexOf('/')+1);
                this.copyFileToLocalDir(correctPath,correntName,this.createFileName());
            }
        },(error)=>{
            super.showToast(this.toastCtrl,'It`s wrong to choose picture, please operate in app or check permission.');
        })
    }
    
    //将获取到的图片或者相机拍摄到的图片进行一下另存为,用于后期的图片上传使用
    copyFileToLocalDir(namePath,currentName,newFileName){
        //使用cordova专门存储临时文件的目录
        this.file.copyFile(namePath,currentName,cordova.file.dataDirectory,newFileName).then(success=>{
            this.lastImage = newFileName;
        },error =>{
            super.showToast(this.toastCtrl,"Something wrong when storage picture into local.");
        });
    }
    
    //为文件生成一个新的文件名
    createFileName() {
        let d = new Date();
        let n = d.getTime();
        let newFileName = n + '.jpg';
        return newFileName;
    }
    
    //处理图片的路径为可以上传的路径
    public pathForImage(img) {
        if(img === null){
            return '';
        }else{
            return normalizeURL(cordova.file.dataDirectory + img);
        }
    }
    
    //上传图片逻辑
    uploadImage() {
        let url = "";//上传的url路径
        let targetPath = this.pathForImage(this.lastImage);
        let fileName = this.userId + ".jpg";//定义上传后的文件名
        //上传的参数
        let options = {
            fileKey:"file",
            fileName:fileName,
            chunkedMode:false,
            mimeType:"mulipart/form-data",
            params:{
                'fileName':fileName,
                'userId':this.userId
            } 
        }
        const fileTransfer:TransferObject = this.transfer.create();
        let loading = super.showLoading(this.loadingCtrl,"上传中...");
        //开始正式上传
        fileTransfer.upload(targetPath,url,options).then((data)=>{
            loading.dismiss();
            super.showToast(this.toastCtrl,"Upload avatar successfully!");
            //在用户看清弹窗提示后进行页面的关闭
            setTimeout(()=>{
                this.viewCtrl.dismiss();
            },2000);
        },err=>{
            loading.dismiss();
            super.showToast(this.toastCtrl,"Upload avatar failed, please retry...");
        });
    }
    

四.不同的系统下测试上传图片功能

执行ionic build命令实现项目打包,将src的源文件打包成对应的已经添加的平台

1.IOS测试

  • 添加build ios的环境
    • sudo cordova platform rm ios
    • sudo cordova platform add ios
    • sudo ionic build ios
  • 使用xcode打开.codeproj文件

2.Android测试

  • 添加build android的环境
    • sudo cordova platform rm android
    • sudo cordova platform add android
    • sudo ionic cordova build android打包生成的文件地址项目根目录/platforms/android/build/outputs/apk/android-debug.apk
  • 使用android studio中打开模拟器运行项目

猜你喜欢

转载自blog.csdn.net/qq_34829447/article/details/84981616