Ionic 4使用Angular HTTP上传图像

问题描述 投票:0回答:1

我使用Ionic 4和Angular 7与PHP作为后端。我正在尝试上传文件(图像/视频/ PDF /音频)。是否有一般发送方式。我尝试使用相机插件发送图像,它返回URI,它使用img标签在应用程序上工作。但是我无法使用formData将文件自动发送给它

openCamera() {

    const options: CameraOptions = {
      quality: 100,
      destinationType: this.camera.DestinationType.FILE_URI,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      sourceType: this.camera.PictureSourceType.PHOTOLIBRARY
    };

    this.camera.getPicture(options).then((imageData) => {
      this.imageData = imageData; 
      this.image = (<any>window).Ionic.WebView.convertFileSrc(imageData); 
       // this.image works fine in img tag
      this.sendMsg(this.image);
    }, (err) => {
      // Handle error
      alert('error ' + JSON.stringify(err));
    });

  }

  sendMsg(file?) {
    const data = new FormData();
    data.set('group_id', this.groupId);
    data.set('text', this.msg);
    if (file) {
      data.set('file', this.image);
      data.set('text', '');
    }

    this.messeges.push(data);

    this._messengerService.postMsg(data).subscribe(
      res => {
        console.log('res ', res);

        if (res.success === true) {
          console.log('data added ', res);

        }
      }
    );
  }

我想使用URI来获取实际文件

file-upload angular7 ionic4
1个回答
0
投票

Ionic Native插件只返回base64。根据您的问题,您需要转换formdata。所以,你需要在外部将base64转换为formdata

  dataURItoBlob(dataURI) {
    // convert base64/URLEncoded data component to raw binary data held in a string
    var byteString;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
      byteString = atob(dataURI.split(',')[1]);
    else
      byteString = unescape(dataURI.split(',')[1]);
    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
    // write the bytes of the string to a typed array
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i);
    }
    return new Blob([ia], { type: mimeString });
  }

 profileUpdate(options) {
    this.camera.getPicture(options).then((imageData) => {
      let base64Image = 'data:image/jpg;base64,' + imageData;
      let data = this.dataURItoBlob(base64Image);
      let formData = new FormData();
      formData.append('profile', data, "filename.jpg");
      //here you pass the formdata to to your API
    })
© www.soinside.com 2019 - 2024. All rights reserved.