【问题标题】:How To set a profile picture functionality in ionic3如何在 ionic3 中设置个人资料图片功能
【发布时间】:2018-07-25 13:24:49
【问题描述】:

在我的项目中,我需要在profile.htmlpage 中保存并向用户显示个人资料图片。

并且还允许用户更改他们的个人资料图片,例如whatsapp

在这里分享我的代码

profile.html

  <ion-content>

    <img src="{{pathForImage(lastImage)}}" style="width: 100%" 
    [hidden]="lastImage === null" class="imgcircle">

     <ion-toolbar color="primary">
      <ion-buttons>

  <button ion-button icon-left (click)="presentActionSheet()">
    <ion-icon name="camera"></ion-icon>Select Image
  </button>

  <button ion-button icon-left (click)="uploadImage()" 
  [disabled]="lastImage=== null">
    <ion-icon name="cloud-upload"></ion-icon>Upload
  </button>

  </ion-buttons>
  </ion-toolbar>

  </ion-content>

profile.ts

   export class HomePage {

   lastImage: string = null;
   loading: Loading;

   constructor(public navCtrl: NavController, private camera: Camera, private 
   transfer: Transfer, private file: File, private filePath: FilePath, public 
   actionSheetCtrl: ActionSheetController, public toastCtrl: ToastController, 
   public platform: Platform, public loadingCtrl: LoadingController) { }

   public presentActionSheet() {
   let actionSheet = this.actionSheetCtrl.create({
   title: 'Select Image Source',
   buttons: [
    {
      text: 'Load from Library',
      handler: () => {
        this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
      }
    },
    {
      text: 'Use Camera',
      handler: () => {
        this.takePicture(this.camera.PictureSourceType.CAMERA);
      }
    },
    {
      text: 'Cancel',
      role: 'cancel'
    }
   ]
  });
   actionSheet.present();
  }
  }

   public takePicture(sourceType) {
  // Create options for the Camera Dialog
   var options = {
    quality: 100,
   sourceType: sourceType,
   saveToPhotoAlbum: false,
   correctOrientation: true
    };

   // Get the data of an image
    this.camera.getPicture(options).then((imagePath) => {
   // Special handling for Android library
    if (this.platform.is('android') && sourceType === 
    this.camera.PictureSourceType.PHOTOLIBRARY) {
    this.filePath.resolveNativePath(imagePath)
    .then(filePath => {
      let correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
      let currentName = imagePath.substring(imagePath.lastIndexOf('/') + 1, 
       imagePath.lastIndexOf('?'));
      this.copyFileToLocalDir(correctPath, currentName, 
       this.createFileName());
     });
    } else {
    var currentName = imagePath.substr(imagePath.lastIndexOf('/') + 1);
    var correctPath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
    this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
     }
     }, (err) => {
    this.presentToast('Error while selecting image.');
     });
      }

     private createFileName() {
      var d = new Date(),
      n = d.getTime(),
      newFileName =  n + ".jpg";
       return newFileName;
       }

      // Copy the image to a local folder
      private copyFileToLocalDir(namePath, currentName, newFileName) {
      this.file.copyFile(namePath, currentName, cordova.file.dataDirectory, 
      newFileName).then(success => {
       this.lastImage = newFileName;
       }, error => {
       this.presentToast('Error while storing file.');
      });
       }

      private presentToast(text) {
      let toast = this.toastCtrl.create({
       message: text,
       duration: 3000,
       position: 'top'
         });
       toast.present();
        }

      // Always get the accurate path to your apps folder
      public pathForImage(img) {
      if (img === null) {
        return '';
         } else {
       return cordova.file.dataDirectory + img;
          }
          }

使用 PHP 上传图片到服务器

        public uploadImage() {
       // Destination URL
        var url = "http://xxxx/img/upload.php";

        // File for Upload
         var targetPath = this.pathForImage(this.lastImage);

        // File name only
        var filename = this.lastImage;

         var options = {
         fileKey: "file",
         fileName: filename,
         chunkedMode: false,
         mimeType: "multipart/form-data",
         params : {'fileName': filename}
        };

          const fileTransfer: TransferObject = this.transfer.create();

           this.loading = this.loadingCtrl.create({
           content: 'Uploading...',
           });
           this.loading.present();

           // Use the FileTransfer to upload the image
         fileTransfer.upload(targetPath, url, options).then(data => {
         this.loading.dismissAll()
         this.presentToast('Image succesful uploaded.');
         }, err => {
         this.loading.dismissAll()
         this.presentToast('Error while uploading file.');
           });
           }

只要用户上传图片,就会成功上传到服务器。

但是上传个人资料图片后,当我转到下一页并返回profile.html页面时,图片将不可见

每当用户查看profile.html 页面时,我想显示个人资料图片。

有什么想法吗??

【问题讨论】:

    标签: ionic-framework ionic3


    【解决方案1】:

    将此代码放入您的 Html 文件中。

      <img src="{{ myphoto }}" (click)="getImage()" width="50%" height="50%" alt="Registration Image">
    

    在你的 .ts 类中设置它。 myphoto:any="assets/imgs/registration_default_image.png";

    这是打开图库和设置图片的方法。

    // 打开图库

    getImage() {

    const options: CameraOptions = {
      quality: 70,
      destinationType: this.camera.DestinationType.DATA_URL,
      sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
      saveToPhotoAlbum:false
    }
    this.camera.getPicture(options).then((imageData) => {
      // imageData is either a base64 encoded string or a file URI
      // If it's base64:
      this.myphoto = 'data:image/jpeg;base64,' + imageData;
    }, (err) => {
      // Handle error
    });
    

    } //结束

    这将从图库中设置您的图像。

    【讨论】:

      【解决方案2】:

      因为您在上传时获取了文件目录 URI。一旦您被选中,它就来自移动目录,并且在页面上暂时可用。转到另一个页面后它消失了。好吧,您可以检查Image标签的条件。

      例如:

      <img src="{{pathForImage(lastImage)}}" style="width: 100%" 
          [hidden]="lastImage === null" class="imgcircle">
      and
      
      <img src="url" style="width: 100%" 
          class="imgcircle" *ngIf="lastImage==null">
      

      您可以在 src 标签中绑定更新后的 url 以查看上传的配置文件并执行两个条件以显示图像。

      网址如https://stackoverflow.com/example.png

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-17
        • 1970-01-01
        • 1970-01-01
        • 2014-09-15
        • 2017-09-30
        • 2013-12-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多