Skip to content

ERROR Error: [object Object] while uploading images in storage  #1439

Closed

Description

@anup5708

Hi Team,

I am developing one application and I have used ionic 3.9.2 and I am trying to upload an image in firebase storage and the angularfire 2 version is 5.0.0-rc.4 and firebase 4.8.0.

I tried to get the image from Camera

 const cameraOptions: CameraOptions = {
      quality: 50,
      destinationType: this.camera.DestinationType.DATA_URL,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
    };

    this.camera.getPicture(cameraOptions).then((imageData) => {
      // imageData is either a base64 encoded string or a file URI
      // If it's base64:
      this.captureDataUrl = 'data:image/jpeg;base64,' + imageData;
    }, (err) => {
      // Handle error
    });

And then uploading the image in firebase storage


import * as firebase from 'firebase';
  let storageRef = firebase.storage().ref();
    // Create a timestamp as filename
    const filename = Math.floor(Date.now() / 1000);

    // Create a reference to 'images/todays-date.jpg'
    const imageRef = storageRef.child(`myname/${filename}.jpg`);

    imageRef.putString(this.captureDataUrl, firebase.storage.StringFormat.DATA_URL).then((snapshot)=> {
      // Do something here when the data is succesfully uploaded!
     });

I am getting an error as

abc.html:217 ERROR Error: [object Object]
    at viewWrappedDebugError (vendor.js:9858)
    at callWithDebugContext (vendor.js:15104)
    at Object.debugHandleEvent [as handleEvent] (vendor.js:14681)
    at dispatchEvent (vendor.js:10058)
    at vendor.js:10672
    at HTMLButtonElement.<anonymous> (vendor.js:40181)
    at t.invokeTask (polyfills.js:3)
    at Object.onInvokeTask (vendor.js:4974)
    at t.invokeTask (polyfills.js:3)
    at r.runTask (polyfills.js:3)

Activity

  1. samcfinan commented on Jan 25, 2018

    @samcfinan

    Hi there,

    I'm using RC6 from @next. Here's how I built my upload service:

    `import { AngularFireStorage, AngularFireStorageReference, AngularFireUploadTask } from 'angularfire2/storage';

    @Injectable()
    export class UploadService {

    constructor(private afStorage: AngularFireStorage) { }

    pushUpload(upload: Upload) {
    const storageRef: AngularFireStorageReference = this.afStorage
    .ref(/uploads/${upload.name});

    return storageRef.put(upload.file);
    

    }

    }
    `

  2. Bengejd commented on Jan 27, 2018

    @Bengejd

    I'm having the same issue as the original poster. Just getting an error with [Object, Object] while trying to upload my image to firebase storage.

  3. codediodeio commented on Jan 28, 2018

    @codediodeio
    Contributor

    Rather than use the entire firebase SDK, why not use AngularFireStorage? Using your camera capture code, I was able to upload successfully:

    constructor(private storage: AngularFireStorage) { }
    
      upload() {
        const img = 'data:image/jpeg;base64,' + base64fromCamera;
        this.storage.ref('cool.jpeg').putString(img, 'data_url');
      }
    
  4. Bengejd commented on Jan 29, 2018

    @Bengejd

    I actually found that I was able to do the same as @codediodeio using

    const path = `test/${new Date().getTime()}_${this.auth.getUid()}.jpg`;
      this.storage.ref(path).putString(photo, 'data_url');
    
  5. alheranx commented on Feb 8, 2018

    @alheranx

    ¿Can you resolve it?
    I have the same error... my mistake was put the URI, and firebase only accept blob or file type. I try make a blob from URL without success, and then the solution was the base64, the same solution I see in documentation. I would like don't have to use base64, it make it slowly my app, but as the firebase implementation is incredible and easy, well I think I can pass for base 64. If I put the URI I duplicate the error, if I put bas64 all works fine.

  6. anup5708 commented on Feb 12, 2018

    @anup5708
    Author

    Hi there,

    I just managed by writing the below code:

    Html File
    <input type="file" (change)="registerNewCandidate($event)" />

    Source Code

    firebase.storage().ref().child('myupload/mountains.jpg').put(event.srcElement.files[0]).then(function(snapshot) {
          snapshot.downloadURL;
    });
    

    I hope this help

  7. Tom-Checkley commented on Mar 5, 2018

    @Tom-Checkley

    I'm getting a very similar error, I'm quite new to this so if I've made a dumb mistake forgive me for time wasting. Also, when other errors occur it's normally quite easy to spot where / why they're happening, this one not so much so if anyone can give any hints to make debugging easier in future I'd be very grateful

    createPost(post: Blog) {
        const storageRef = firebase.storage().ref();
        storageRef.child(`blogImg/${post.imgTitle}`).putString(post.img, 'base64')
          .then((snapshot) => {
            const url = snapshot.metadata.downloadURLs[0];
            const dbRef = firebase.database().ref('blogPosts/');
            const newPost = dbRef.push();
            newPost.set({
              title: post.title,
              content: post.content,
              location: post.location,
              imgTitle: post.imgTitle,
              img: url,
              id: newPost.key
            });
          })
          .catch((err) => {
            alert(`failed upload: ${err}`);
          });
      }
    BlogAddComponent.html:4 ERROR Error: [object Object]
        at viewWrappedDebugError (core.js:9764)
        at callWithDebugContext (core.js:15066)
        at Object.debugHandleEvent [as handleEvent] (core.js:14643)
        at dispatchEvent (core.js:9962)
        at eval (core.js:12301)
        at SafeSubscriber.schedulerFn [as _next] (core.js:4343)
        at SafeSubscriber.__tryOrUnsub (Subscriber.js:240)
        at SafeSubscriber.next (Subscriber.js:187)
        at Subscriber._next (Subscriber.js:128)
        at Subscriber.next (Subscriber.js:92)
  8. codediodeio commented on Apr 1, 2018

    @codediodeio
    Contributor
  9. Aadencoder commented on Apr 2, 2018

    @Aadencoder

    Hello Codediodeio thanks for your blog post. I will check that out.

  10. rogeraleite commented on Apr 5, 2018

    @rogeraleite

    Hello everyone,
    I am also having the same problem. I have already tried:

                      //1 - ..putString(image) works!! But uploaded image can not be readed because it gets type "application/octet-stream" 
                      //this.storage.ref(filePath).putString(image);
    
                      //2 - Error: Uncaught (in promise): [object Object]
                      //this.storage.ref(filePath).put(image);
    
                      //3 - Error: Uncaught (in promise): [object Object]
                      //this.storage.ref(filePath).putString(image, 'data_url');
    
                      //4 - Error: Uncaught (in promise): [object Object]
                      //this.storage.upload(filePath,image);
    
                      //5 - Error: Uncaught (in promise): [object Object]
                      //this.storage.ref(filePath).putString(image,'base64');
    
                      //6 - ERROR Error: Uncaught (in promise): [object Object]
                      //this.storage.ref(filePath).putString(image,'base64url');
    
                      //7 - ERROR Error: Uncaught (in promise): [object Object]
                      //this.storage.ref(filePath).putString(image,'data_url');
    
                      //8 - ERROR Error: Uncaught (in promise): [object Object]
                      //this.storage.ref(filePath).put(image, metadata);
    
                      //9 - ERROR Error: Uncaught (in promise): [object Object]
                      // var storageRef = firebase.storage().ref();
                      // var imagesRef = storageRef.child(filePath);
                      // imagesRef.put(image,metadata);
    
                      //10 - ERROR Error: Uncaught (in promise): [object Object]
                      // if(image){
                      //   firebase.storage().ref().child(filePath).put(image).then((snapshot) => {
                      //     console.log("snapshot.downloadURL" ,snapshot.downloadURL);
                      //   });
                      // }
    

    no success with neither =/.

    Any suggestions?

  11. hiepxanh commented on Apr 20, 2018

    @hiepxanh
    Contributor

    i don't know why you have problem, I was able to upload successfully too:

     accessGallery(sourceType:number) {
      // this.accessGallery(0) for photo library
      // this.accessGallery(1) for camera
    
    const options: CameraOptions = {
      quality: 100,
      destinationType: this.camera.DestinationType.DATA_URL,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      correctOrientation: true,
      sourceType:sourceType,
    }
    this.camera.getPicture(options).then((imageData) => {
      // imageData is either a base64 encoded string or a file URI
      // If it's base64:
      this.base64Image = 'data:image/jpeg;base64,' + imageData;
      this.images.push(this.base64Image);
      this.upload(this.base64Image);
    }, (err) => {
     // Handle error
    });
    }
    
    
     upload(event) {
    // way 2
    this.afStorage.ref(`products/${Date.now()}.jpeg`).putString(event, 'data_url')
    .then(url => console.log("upload success",url))
    }
    

    then you can access camera or get image from library and upload it

    <button (click)="accessGallery(0)">select image then upload</button>
    <button (click)="accessGallery(1)">capture image then upload</button>
    

    enter image description here

    `

  12. jamesdaniels commented on May 4, 2018

    @jamesdaniels
    Contributor

    Going to close since it's not clear that this is an issue with AF2, please provide a repro if you reopen.

  13. mikeCm14 commented on May 26, 2018

    @mikeCm14

    @codediodeio Will the code in your post work with iOS devices? I'm having issues uploading from iPhone

  14. codediodeio commented on May 26, 2018

    @codediodeio
    Contributor

    @Heckthor it should in theory, but iOS can have some quirks that vary. Can you post the error and details on stack overflow?

  15. mikeCm14 commented on May 26, 2018

    @mikeCm14

    OK, I'll post the details in a few minutes.

    Thanks

  16. mikeCm14 commented on May 26, 2018

    @mikeCm14

    @codediodeio Here is the Stack overflow post

    Hopefully, you can think of something, I've spent all day trying to figure it out.

  17. mikeCm14 commented on May 28, 2018

    @mikeCm14

    @codediodeio I know what happened. My super slow, third-world country network was responsible. The pictures uploaded a few hours later while I was sleeping. Thanks, though.

  18. Robinyo commented on Sep 13, 2018

    @Robinyo

    @Heckthor

    I just noticed an issue with my Ionic 3/Angular 5 PWA (that uses angularfire2) when trying to upload files on iOS 11.4.1.

    It turns out it is related to Safari's experimental support for Service Workers.

    my-page-component.ts:

    ...
    import { AngularFireStorage, AngularFireUploadTask } from 'angularfire2/storage';
    import { Observable } from 'rxjs/Observable';
    ...
    
      private downloadURL: Observable<string>;
    
      public uploadFile(event) {
    
        const file = event.target.files[0];
        const filePath = 'reviews' + '/' + this.beer.id + '/' + this.authService.getUserId();
        const task: AngularFireUploadTask = this.afStorage.upload(filePath, file);
    
        this.downloadURL = task.downloadURL();
    
        this.downloadURL.subscribe((url) => {
    
          // do stuff
    
        });
      }
    

    main.ts:

    platformBrowserDynamic().bootstrapModule(AppModule).then(() => {
    
      const isIos = () => {
        const userAgent = navigator.userAgent.toLowerCase();
        return /iphone|ipad|ipod/.test(userAgent);
      };
    
      if (isIos()) {
    
        // https://github.com/angular/angular/issues/23244
        console.log('Service Worker not registered');
    
      } else {
    
        // https://stackoverflow.com/questions/48723206/angular-5-service-worker-not-working
        // Seems to be a problem in registering service worker in module where also importing AngularFire2
        if ('serviceWorker' in navigator && ENV.production) {
          navigator.serviceWorker.register('/ngsw-worker.js');
          console.log('Service Worker registered');
        }
    
      }
    
    }).catch(error => console.log(error));
    
  19. jek-bao-choo commented on Aug 3, 2019

    @jek-bao-choo
    Contributor
  20. JayPerfetto commented on Mar 8, 2020

    @JayPerfetto

    This can also happen when using the package Ng2-file-uploader -> you need to reference item.file.rawFile instead of just item.file in your put data:

    upload(event) { const item = this.uploader.queue[0]; console.log(item); const id = Math.random().toString(36).substring(2); console.log(id); this.ref = this.storage.ref(item.file.name); this.task = this.ref.put(item.file.rawFile); this.uploadProgress = this.task.percentageChanges(); this.task.snapshotChanges().pipe( finalize(() => { this.ref.getDownloadURL().subscribe(url => { console.log(url); }); })) .subscribe(); }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions