-1

I am using Angular js with ASP.NET MVC and file upload done using codepen method.

It is running fine because I want to store the binary array so I can convert later and set it back.

But the problem I am facing is to validate the selected thing is image or not!

I can't find the way how can I check the selected thing is image or not?

Anyone have any idea about this?

I have also used parsley js for validation but it is angular js here also how can I use parsley to validate the selected thing is image or not or manually?

3 rules
  • 1,359
  • 3
  • 26
  • 54
  • Do you mean you want restrict the user to upload images or what ? If this is case you can restrict the file input images only by adding accept="image/*" attribute in html file input element. – Gavishiddappa Gadagi Mar 03 '17 at 10:07
  • @GavisiddaGadagi Sir I appreciate your answer and it is right but I have used different kind of upload function please see the link provided in the question. I want validation on that! – 3 rules Mar 03 '17 at 14:16

1 Answers1

0
    angular.module('starter', [])
      .controller('Ctrl', function($scope) {
        $scope.data = {}; //init variable
        $scope.click = function() { //default function, to be override if browser supports input type='file'
          $scope.data.alert = "Your browser doesn't support HTML5 input type='File'"
        }

        var fileSelect = document.createElement('input'); //input it's not displayed in html, I want to trigger it form other elements
        fileSelect.type = 'file';

        if (fileSelect.disabled) { //check if browser support input type='file' and stop execution of controller
          return;
        }

        $scope.click = function() { //activate function to begin input file on click
            fileSelect.click();
        }

        fileSelect.onchange = function() { //set callback to action after choosing file
          var f = fileSelect.files[0], r = new FileReader();    
          if(f.type === 'image/jpeg' || f.type === 'image/png') {
            console.log('The file type is ' + f.type);
             // do something here
          } else {
            console.log('The file type is ' + f.type);
            // do some other thing here
          }
          r.onloadend = function(e) { //callback after files finish loading
              $scope.data.b64 = e.target.result;
              $scope.$apply();                  console.log($scope.data.b64.replace(/^data:image\/(png|jpg);base64,/, "")); //replace regex if you want to rip off the base 64 "header"        
              //here you can send data over your server as desired
          }

            r.readAsDataURL(f); //once defined all callbacks, begin reading the file

        };


  });

or you can dynamically set accept="image/*" attribute to your html element.

check here

Community
  • 1
  • 1
Gavishiddappa Gadagi
  • 1,120
  • 1
  • 16
  • 34