2

I'm getting an image upload, or from the camera in an Angular app:

<button type="button" onclick="userData.store()">send now</button><br>
<input type="file" label="add photo" accept="image/*;capture=camera">

Then (for now) handling it with this Javascript:

var input = document.querySelector('input[type=file]');
var issuediv = document.getElementById('issue');

input.onchange = function () {
  var file = input.files[0];
  displayAsImage(file);
};

function displayAsImage(file) {
  var imgURL = URL.createObjectURL(file),
  img = document.createElement('img');
  img.onload = function() {
    URL.revokeObjectURL(imgURL);
  };
  img.src = imgURL;
  issuediv.appendChild(img);
}

Two issues:

  1. This isn't Angular code—is what would be an Angular-ish way of handling the image and preparing it for the (MySQL) database via JSON?
  2. The above displays the image blob in Firefox and Chrome, but iOS and Android browsers don't appear to append the img tag and display only a tiny thumbnail.

1 Answer 1

3

You could use Daniel Afarid's Angular File Upload

Controller

$scope.selectedFiles = [];
$scope.dataUrls = [];
$scope.model = 'test model';

$scope.onImageSelect = function($files) {

    $scope.selectedFiles['image'] = $files[0];


    var $file = $files[0];
    if (window.FileReader && $file.type.indexOf('image') > -1) {
        var fileReader = new FileReader();
        fileReader.readAsDataURL($files[0]);

        fileReader.onload = function(e) {
        $timeout(function() {
        $scope.dataUrls['image'] = e.target.result;
            });
        }
    }    

}

$scope.save_image =  function(){

        $upload.upload({
                  data:$scope.model,
                  url: 'the/url',
                  file: $scope.selectedFiles['image']

        }).then(//success and error callbacks);


    }

View

<form enctype="multipart/form-data" class="form-horizontal">
    <input type="file" ng-file-select="onImageSelect($files)">
    <br />
    <img ng-show="dataUrls['image']" ng-src="{{dataUrls['image']}}">
    <button ng-click="save_image()"></button>
</form>
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, fine in Chrome, but what about when window.FileReader is undefined (e.g. Safari 5.1.10, or in IE9)? Angular File Upload seems to have fallbacks, but the implementation looks complex.
The other part of the question was how to prepare the image data as a sendable payload for database storage?
the window.FileReader is only used to capture the "to be uploaded" file and display to the user. You can still upload images without it
The image data is sent as formdata to the server you can access it as you would any normal file upload from a browser

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.