javascript - 如何检查 Angular JS 中上传文件的类型?

标签 javascript angularjs

我使用图书馆 Angular File Uploader在 Angular JS 中。以下是允许将文件类型设置为上传的过滤器。 我喜欢这样做:

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;
   }
});

问题是用户可以更改扩展文件,例如将 *.exe 更改为 *.pdf,然后 Angular uploader 会将文件添加到上传队列。

以及如何在模板中显示 PDF 和 txt 文件所在的信息?

最佳答案

您已经确定了将文件上传到服务器的主要问题之一(恭喜!):)

撇开玩笑和轻率不谈,我还没有听说过在上传前使用 AngularJS 验证文件的优雅或万无一失的方法(如您所知,AngularJS 受限于 JavaScript 原生提供的 API,因为 AngularJS 是一种 JavaScript框架。)

作为this answer to "How to check file MIME type with javascript before upload?"指出,您可以在上传前在客户端检查文件的 MIME 类型。

但是,由于多种原因,在客户端检查文件存在限制,包括:

  1. 用户可以更改有关文件的信息(例如,正如您指出的那样,扩展名)
  2. 某些浏览器对 API 的支持有限,这些 API 可能使您能够首先在客户端检查文件

这就是为什么最好的办法是检查服务器上的文件

一种方法(在可能的许多方法中)是使用 PHP,并执行类似于 this answer to "How to check file types of uploaded files in PHP?" 的操作。建议,即:

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.

依靠服务器(而不是客户端)检查文件的优势是您仅受限于您的服务器可以使用的 API(客户端用户无法控制)。

关于javascript - 如何检查 Angular JS 中上传文件的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30152719/

相关文章:

javascript - 如何在 Ext.Panel 标题中放置文本和可点击图标?

javascript - 如何从 CSV 文件填充 Ng-Grid?

angularjs - 如何使用来自同一来源的不同值设置默认选定的下拉列表

javascript - Asp 网络核心 MVC : Passing a list of string as a parameter in javascript

javascript - 如何在 react 中用鼠标选择范围单元格?

javascript - Dojo 多个带有下拉按钮的非模式对话框

javascript - 如何定义 ng-options 选择值并将其分配给模型?

php - 当组合框 #1 更改值时刷新页面和组合框 #2 内容

javascript - 异步 forEach AngularJS 后的回调

javascript - Bower 同时安装两个版本的 Angular