How to detect the uploaded file type in angularJS

时间秒杀一切 提交于 2020-01-01 10:01:23

问题


I have an form to upload only image file using angularJS. Uploading the file is all working fine. The problem is, I want to restrict the uploaded file to be only image file and also the size of the image to be some MB. How can I achieve this using only angularJS? Below is the code

$scope.uploadFile = function(files) {
    var fd = new FormData();
    //Take the first selected file
    fd.append("file", files[0]);

    $http.post("logoTypesServiceStore", fd, {
        withCredentials: true,
        headers: {'Content-Type': undefined },
        transformRequest: angular.identity
    }).success( function(data) {alert(data); }).error( function(data) { alert(data)});

};  

Below is the form to upload file.

 <form name="logoTypeForm" novalidate>
     <input type="text" name="logoType" ng-model="logoType" class="form-control" required />
     <input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this.files)"/>

 </form>

回答1:


Modern browsers have File API support.

$scope.uploadFile = function(files) {
    files[0].type; //MIME type
    files[0].size; //File size in bytes
}; 

Here is a list of image MIME types




回答2:


I would recommend to already specify the files you would like to accpet within your input tag like so:

<input type="file" name="files" accept="image/*">

For more information check out the W3Schools reference for the input tag.



来源:https://stackoverflow.com/questions/24158365/how-to-detect-the-uploaded-file-type-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!