Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check type of uploading file in Angular JS?

I use library Angular File Uploader in Angular JS. Here are filters thats allow to set files types to uploading. I do it like as:

uploader.filters.push({
    name: 'imageFilter',
    fn: function (item /*{File|FileLikeObject}*/, options) {
    var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
         return '|doc|txt|docx|xml|pdf|djvu'.indexOf(type) !== -1;
   }
});

Problem is that user can change extension file, for example change *.exe to *.pdf and after Angular uploader will add file to queue upload.

And how I can show information in template where is PDF and txt file?

like image 208
Hamed Avatar asked Nov 09 '22 13:11

Hamed


1 Answers

You've identified one of the major concerns with uploading files to a server (congratulations!) :)

All joking and flippancy aside, I haven't heard of an elegant or sure-fire way to validate files with AngularJS before upload (as you know, AngularJS is limited by the APIs that JavaScript natively provides, since AngularJS is a JavaScript framework.)

As this answer to "How to check file MIME type with javascript before upload?" points out, you can check the MIME type of a file on the client before uploading.

However, there are limitations to checking files on the client for many reasons, including:

  1. The user can change information about the file (for example, as you pointed out, the extension name)
  2. Some browsers have limited support for the APIs that might enable you to check files in the first place on the client

That's why your best bet is to check files on the server.

One method (among the probable many) is to use PHP, and do something similar to what this answer to "How to check file types of uploaded files in PHP?" suggests, which is:

Take a look at mime_content_type or Fileinfo. These are built-in PHP commands for determining the type of a file by looking at the contents of the file. Also check the comments on the above two pages, there are some other good suggestions.

Personally I've had good luck using something that's essentially system("file -bi $uploadedfile"), but I'm not sure if that's the best method.

The advantage of relying on the server (instead of the client) to check files is you are only limited by the APIs that your server can utilize (which the client user has no control over).

like image 110
Josh Beam Avatar answered Nov 14 '22 22:11

Josh Beam