简体   繁体   English

Javascript-上传文件内容类型验证

[英]Javascript - Upload file content type validation

How to validate the content-type of a file before uploading using JavaScript? 在使用JavaScript上传之前,如何验证文件的内容类型? I'm not asking the extension validation . 我不问扩展验证 I want to validate pdf,plain text and MS word files. 我想验证pdf,纯文本和MS word文件。

I'm using a django forms.ModelForm to pass file upload widget to html. 我正在使用django forms.ModelForm将文件上传小部件传递给html。 I couldn't achieve this either on server side. 我在服务器端都无法实现。 Here is that question, 这是这个问题,

Django - Uploaded file type validation Django-上传的文件类型验证

In theory you could use the File API to read the files. 理论上,您可以使用File API读取文件。

You would then need to write parsers in JavaScript for the file formats you cared about to check if they matched. 然后,您需要使用JavaScript编写解析器,以检查您想要检查的文件格式是否匹配。

Maybe but it won't give you any form of security because an attacker could use other means to upload files thus circumventing your validation. 也许可以,但是它不会为您提供任何形式的安全性,因为攻击者可以使用其他方式上传文件,从而绕过您的验证。

To check the file type using the extension (which is very insecure since it's dead easy to manipulate it), you can use JavaScript. 要使用扩展名检查文件类型(这是非常不安全的,因为它很难操作),可以使用JavaScript。 See this question: How do I Validate the File Type of a File Upload? 看到以下问题: 如何验证文件上传的文件类型?

[EDIT] After some googling , I found that the input element has an attribute accept which takes a list of mime type patterns. [编辑]经过一番谷歌搜索后 ,我发现input元素具有一个accept属性,该属性accept mime类型模式的列表。 Unfortunately, most browsers ignore it (or only use it to tweak the file selection dialog). 不幸的是,大多数浏览器都忽略了它(或仅使用它来调整文件选择对话框)。 See this question: File input 'accept' attribute - is it useful? 看到以下问题: 文件输入'accept'属性-有用吗?

[EDIT 2] Right now, it seems that the File API (see " Using files from web applications ") is your only way it you really don't want to use file extensions. [EDIT 2]现在,看来File API(请参阅“ 使用Web应用程序中的文件 ”)是您真正不想使用文件扩展名的唯一方法。 Each File instance has a type property which contains the mime type. 每个File实例都有一个type属性,其中包含mime类型。

But this API is work in progress, so it's not available everywhere. 但是此API尚在开发中,因此并非在所有地方都可用。 And there is no guarantee that you'll get a MIME type (the property can be "" ). 并且不能保证您将获得MIME类型(该属性可以是"" )。

So I suggest this approach: Try the File API. 因此,我建议采用这种方法:尝试File API。 If it's not available or the type property is empty, use the file extension. 如果不可用或type属性为空,请使用文件扩展名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM