Shashwat Gupta
Shashwat Gupta

Reputation: 5264

How to send base64 in fromdata to nodejs server from ionic or angular?

corroupted file savedfile comes on backend like this objectBackend save file on file system pickImage(sourceType) { const options: CameraOptions = { quality: 100, sourceType: sourceType, destinationType: this.camera.DestinationType.DATA_URL, encodingType: this.camera.EncodingType.JPEG, mediaType: this.camera.MediaType.PICTURE, correctOrientation: true, }; // this.camera.getPicture(options).then((imageData) => {

    this.camera.getPicture(options).then(
      (imageData) => {


        const formData = new FormData();

        formData.append('file', imageData);
        let newName = this.randomString(6) + new Date().getTime() + "." + file.type;

        alert(JSON.stringify(formData));

 this.http.post("//localhost:3000/api/v1/Admin/saveAllImages", formData)
        .pipe(
            finalize(() => {
                // loading.dismiss();
            })
        )
        .subscribe(res => {
            if (res['success']) {
                this.presentToast('File upload complete.')
            } else {
                this.presentToast('File upload failed.')
            }
        });
    };

}

Upvotes: 0

Views: 904

Answers (1)

Aakash Garg
Aakash Garg

Reputation: 10979

let formData = new FormData();
let blob = this.DataURIToBlob(this.imageData);
formData.append('file', blob)


DataURIToBlob(dataURI: string) {
        const splitDataURI = dataURI.split(',')
        const byteString = splitDataURI[0].indexOf('base64') >= 0 ? atob(splitDataURI[1]) : decodeURI(splitDataURI[1])
        const mimeString = splitDataURI[0].split(':')[1].split(';')[0]

        const ia = new Uint8Array(byteString.length)
        for (let i = 0; i < byteString.length; i++)
            ia[i] = byteString.charCodeAt(i)

        return new Blob([ia], { type: mimeString })
      }

Upvotes: 1

Related Questions