Search code examples
angularmobilecamera

Angular 2-12 Mobile Camera Capture


I'm looking for a way to use the mobile camera to capture a photo and upload it to a server in Angular 2+. Is it possible to do it?

I can find a lot of uploading files tutorials but not even one which tutoring how to access the mobile camera and use the captured photo.


Solution

  • OK, so I finally got what I need. In the .html file:

    <input type="file" capture="camera" accept="image/*" id="cameraInput" name="cameraInput" (change)="onFileSelected($event)">
    <button type="button" (click)="onUpload()">Upload File</button>

    in the .ts file:

    export class AppComponent {
      title = 'app';
      selectedFile = null;
    
      onFileSelected(event)
      {
        this.selectedFile = event.target.files[0];
      }
    
      onUpload()
      {
        console.log(this.selectedFile); // You can use FormData upload to backend server
      }
    }

    Use "selectedFile" variable to whatever you need to do with your photo.

    Note: It only works on iOS6+, I have checked on android and it works well.