-1

我正在使用带有 ASP.NET MVC 的 Angular js,并使用codepen方法完成文件上传。

它运行良好,因为我想存储二进制数组,以便稍后转换并将其设置回来。

但我面临的问题是验证所选内容是否为图像!

我找不到如何检查所选内容是否为图像的方法?

有人对此有任何想法吗?

我也使用欧芹 js 进行验证,但它是 angular js,我如何使用欧芹来验证所选的东西是图像还是手动?

4

1 回答 1

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

        };


  });

或者您可以为您的 html 元素动态设置 accept="image/*" 属性。

在这里检查

于 2017-03-03T17:52:16.017 回答