ngx-image-cropper Output property file having undefined name

2.9k Views Asked by At

I am using ngx-image-cropper to crop an image in my angular app. I use the Output property returning 'File' which is (imageCroppedFile) to be able to grab the cropped image. I need the cropped image to have a file name, so that I can iterate through the files on the back end using the name attribute, while it is by default undefined. How can I give it a name? I tried the following: On the FormData,

var formData:any = new FormData();
console.log('The number of files is '+files.length);//Logs the number of files is 1

for(var i=0; i<files.length;i++) {
  formData.append("uploads[]", files[i].name, 'image'+i);
  console.log('File name '+ i + ' ' +files[i].name);//Logs File name 0 undefined
}

and on the method triggered by the cropping

imageCroppedFile(image: File) {
  this.filesToUpload = [];
  console.log('imageCroppedFile method '+image.name+ ' size is '+image.size);// Logs imageCroppedFile method undefined size is 380284
  this.filesToUpload[0]=image;
  console.log('The filesToUpload is '+this.filesToUpload[0].name);// Logs The filesToUpload is undefined
}

The uploader works without the cropper.

2

There are 2 best solutions below

1
On

cast your file into blob, and you can name your blob by yourself

const blobImage = file as Blob;

Reference : https://github.com/Mawi137/ngx-image-cropper/issues/91#issuecomment-422252629

0
On

This works for me:

// grab the cropped area to file for upload
var b64File = this.dataURLtoFile(this.croppedImage, 'hello.jpg');  // you can name it anything.

dataURLtoFile(dataurl, filename): File {
        var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while(n--){
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, {type:mime});
    }