首页 > 解决方案 > 如何在文件更改事件中从 Angular 中的 ngx-image 裁剪器裁剪后将图像上传到节点

问题描述

下面是我的功能

UploadImage(){
  let file: File = this.fileToReturn; //fileToReturn is returned file from the cropper
  let formData:FormData = new FormData();
  formData.append('uploadFile', file, file.name);
  console.log(JSON.stringify(formData))

  formData.forEach((value,key) => {
     console.log(key+" "+value)
   })
  this.authservice.uploadPhoto(formData)
  .subscribe(
    (response) => {
      console.log('response received is ', response); 
    }
  )
  // debugger;
  // console.log(formData);
}

将值记录到控制台和服务器后,我得到空的 json '{}'。应该做什么?我必须使用任何其他库吗?

标签: node.jsangularexpressangular8

解决方案


UploadImage(){
  let file: File = this.fileToReturn;
  let formData:FormData = new FormData();
  formData.append('uploadFile', file, file.name);
  console.log(JSON.stringify(formData))

  formData.forEach((value,key) => {
     console.log(key+" "+value)
   })
  this.authservice.uploadPhoto(formData)
  .subscribe(
    (response) => {
      console.log('response received is ', response); 
      this.openSnackBar('Profile picture updated!','Close');
      // this.shared_user.getProfilepic(response);
    }
  )
  // debugger;
  // console.log(formData);
}
base64ToFile(data, filename) {

  const arr = data.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  let u8arr = new Uint8Array(n);

  while(n--){
      u8arr[n] = bstr.charCodeAt(n);
  }

  return new File([u8arr], filename, { type: mime });
}

imageCropped(event: ImageCroppedEvent) {
      this.croppedImage = event.base64;
      console.log(this.croppedImage);
      this.fileToReturn = this.base64ToFile(
        event.base64,
        this.imageChangedEvent.target.files[0].name,
      )
      return this.fileToReturn
  }

这对我有用


推荐阅读