【问题标题】:How to know selected file is image or not using angular js?如何知道所选文件是图像还是不使用 Angular js?
【发布时间】:2017-07-23 08:45:24
【问题描述】:

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

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

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

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

有人对此有任何想法吗?

我也使用了 parsley js 进行验证,但这里是 angular js 我如何使用 parsley 来验证所选的东西是图像还是手动?

【问题讨论】:

  • 你的意思是你想限制用户上传图片还是什么?如果是这种情况,您只能通过在 html 文件输入元素中添加 accept="image/*" 属性来限制文件输入图像。
  • @GavisiddaGadagi 先生,感谢您的回答,这是正确的,但我使用了不同类型的上传功能,请参阅问题中提供的链接。我想对此进行验证!

标签: angularjs validation base64 image-upload parsley


【解决方案1】:
    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/*" 属性。

check here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    • 2012-07-01
    • 2018-09-19
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多