Umaima Zulfiqar
Umaima Zulfiqar

Reputation: 71

Getting white small pic on upload image to s3bucket in angular ionic

I have "add-property.service.ts" service file which contains calling of APIs and stuff like image upload to s3. This is my code for uploading image to s3. Where I've used ionic documentation to save picture in function "addNewToGallery()" after that I convert it to ".jpeg" extention then to base 64.

now when form submission button clicks i call this function "uploadingImagesToS3Bucket()" to upload the above saved images to s3. on uploading it to s3 i got a white small box in picture but not the actual picture that i wanted.

In my "s3.service.service.ts" file you can check the code for uploading. I think the buffer here is not working I tried to apply "buffer.form" too but result was same. Now I don't know what's the problem is, please help me solve this issue as I'm new to ionic angular.

If you think that converting to .jpeg and to base64 is unnecessary then please tell me, I'll change my code. I only added them to upload picture in correct format before conversion "blob" address was uploading.

//add-property.service.ts :

//S3-Sevice
import { S3ServiceService } from '../../services/s3-service/s3-service.service';
.
.
export class AddPropertyService {
 constructor(
    public s3:S3ServiceService
  ) { }
.
.

  public async addNewToGallery() {
    // Take a photo
    const capturedPhoto = await Camera.getPhoto({
      resultType: CameraResultType.Uri,
      source: CameraSource.Camera,
      quality: 100
    });

    // Save the picture and add it to photo collection
    const savedImageFile = await this.savePicture(capturedPhoto);
    this.photos.unshift(savedImageFile);
  }

  uploadImage(image) {
    return new Promise((resolve) => {
      this.s3.upload(image)  //HERE IM USING UPLOAD FUNCTION FROM S3.SERVICE.SERVICE.TS FILE
    .then(
          res => {
            // console.log("RESULT",res);
            // alert("Image uploaded!");
            resolve(res["Location"])
            this.locationOfImages.unshift(res["Location"]);
            //console.log(this.locationOfImages)
          },
          err => {
            console.log("ERROR",err);
            alert("Error in image upload!");
          }
        );
    })
  }

  public uploadingImagesToS3Bucket(): Promise<any>{  //THIS IS THE FUNCTION I CALL FROM MY ADD-PROPERTY.SERVICE.TS FILE ON CLICKING SUBMITTING FORM BUTTON
                                                     
    let promises = []
    for (let photo of this.photos) {
      promises.push(this.uploadImage(photo.filepath));
    }
    return Promise.all(promises)
  }

 private async savePicture(cameraPhoto: CameraPhoto) {
  // Convert photo to base64 format, required by Filesystem API to save
  const base64Data = await this.readAsBase64(cameraPhoto);
  console.log(cameraPhoto,"cameera photo");
  // Write the file to the data directory
  const fileName = new Date().getTime() + '.jpeg';
  const savedFile = await Filesystem.writeFile({
    path: fileName,
    data: base64Data,
    directory: FilesystemDirectory.Data
  });
  // Use webPath to display the new image instead of base64 since it's
  // already loaded into memory
  return {
    filepath: fileName,
    webviewPath: cameraPhoto.webPath
  };
 }

private async readAsBase64(cameraPhoto: CameraPhoto) {
  // Fetch the photo, read as a blob, then convert to base64 format
  const response = await fetch(cameraPhoto.webPath!);
  const blob = await response.blob();

  return await this.convertBlobToBase64(blob) as string;
}

convertBlobToBase64 = (blob: Blob) => new Promise((resolve, reject) => {
  const reader = new FileReader;
  reader.onerror = reject;
  reader.onload = () => {
      resolve(reader.result);
  };
  reader.readAsDataURL(blob);
});
}

//s3.service.service.ts :

import * as aws from "aws-sdk";
.
.
export class S3ServiceService {

  constructor() { }
  async upload(image) {
    return new Promise((resolve, reject) => {

      var s3 = new aws.S3({
        accessKeyId: environment.ID,
        secretAccessKey: environment.SECRET,
        params: { Bucket: environment.S3.BUCKET_NAME }
      });

      let buf = new Buffer(image, "base64");
      console.log(buf,"buffer");

      var data = {
        Bucket: environment.S3.BUCKET_NAME,
        Key: image,
        Body: buf,
        ContentEncoding: "base64",
        ContentType: "image/jpeg"
      };

      s3.upload(data, (err, res) => {
        if (err) {
          reject(err);
          console.log("Reject",err);
        }
        //console.log(`File uploaded successfully. ${res.Location}`);
        else {
          resolve(res);
        }
      });
    });
  }

Upvotes: 0

Views: 1070

Answers (1)

Umaima Zulfiqar
Umaima Zulfiqar

Reputation: 71

Solved it by changing base64 to byte code. in above functions did the following changes and now image is uploading to s3 bucket.

//add-property.service.ts :

public async addNewToGallery() {
    // Take a photo
    const capturedPhoto = await Camera.getPhoto({
      resultType: CameraResultType.Uri,
      source: CameraSource.Camera,
      quality: 100,
      allowEditing:true
    });

    // Save the picture and add it to photo collection
    const savedImageFile = await this.savePicture(capturedPhoto);

    var afterDot = savedImageFile.image.substr(savedImageFile.image.indexOf(',') + 1 );
    const rawData = atob(afterDot);
   const bytes = new Array(rawData.length);
   for (var x = 0; x < rawData.length; x++) {
       bytes[x] = rawData.charCodeAt(x);
   }
    this.photos.unshift({
      webviewPath:capturedPhoto.webPath,
      filepath: savedImageFile.filepath,
      image: bytes
    });
  }

 uploadImage(image) {
    return new Promise((resolve) => {
      this.s3.upload(image)
    .then(
          res => {
            // console.log("RESULT",res);
            // alert("Image uploaded!");
            resolve(res["Location"])
            this.locationOfImages.unshift(res["Location"]);
            //console.log(this.locationOfImages)
          },
          err => {
            console.log("ERROR",err);
            alert("Error in image upload!");
          }
        );
    })
  }

  public uploadingImagesToS3Bucket(): Promise<any>{
    let promises = []
    for (let photo of this.photos) {
      promises.push(this.uploadImage(photo));
    }
    return Promise.all(promises)
  }

 private async savePicture(cameraPhoto: CameraPhoto) {
  // Convert photo to base64 format, required by Filesystem API to save
  const base64Data = await this.readAsBase64(cameraPhoto);
  console.log(cameraPhoto,"cameera photo");
  // Write the file to the data directory
  const fileName = new Date().getTime() + '.'+cameraPhoto.format;
  const savedFile = await Filesystem.writeFile({
    path: fileName,
    data: base64Data,
    directory: FilesystemDirectory.Data
  });
  // Use webPath to display the new image instead of base64 since it's
  // already loaded into memory
  return {
    filepath: fileName,
    image: base64Data
  };
  }

 private async readAsBase64(cameraPhoto: CameraPhoto) {
  // Fetch the photo, read as a blob, then convert to base64 format
  const response = await fetch(cameraPhoto.webPath!);
  const blob = await response.blob();

  return await this.convertBlobToBase64(blob) as string;
 }

 convertBlobToBase64 = (blob: Blob) => new Promise((resolve, reject) => {
  const reader = new FileReader;
  reader.onerror = reject;
  reader.onload = () => {
      resolve(reader.result);
  };
  reader.readAsDataURL(blob);
 });

//s3.service.service.ts :

 async upload(image) {
    return new Promise((resolve, reject) => {
    console.log(image)
      var s3 = new aws.S3({
        accessKeyId: environment.ID,
        secretAccessKey: environment.SECRET,
        params: { Bucket: environment.S3.BUCKET_NAME }
      });

      let buf = new Buffer(image.image, "base64");
      console.log(buf,"buffer");

      var data = {
        Bucket: environment.S3.BUCKET_NAME,
        Key: image.filepath,
        Body: buf,
        ContentEncoding: "base64",
        ContentType: "image/jpeg"
      };

      s3.upload(data, (err, res) => {
        if (err) {
          reject(err);
          console.log("Reject",err);
        }
        //console.log(`File uploaded successfully. ${res.Location}`);
        else {
          resolve(res);
        }
      });
    });
  }

Upvotes: 0

Related Questions