Html 如何限制 <input type="file"> 使其只能选择 .pdf 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4634159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 06:02:32  来源:igfitidea点击:

How to restrict <input type="file"> so that it can only select .pdf files?

htmlpdffile-io

提问by fms

By default it can select all type of files,how to restrict it so that it can only select .pdffiles?

默认情况下它可以选择所有类型的文件,如何限制它使其只能选择.pdf文件?

采纳答案by David

You can use the acceptattribute on your form to suggest to the browser to restrict certain types. However, you'll want to re-validate in your server-side code to make sure. Never trust what the client sends you.

您可以使用表单上的accept属性向浏览器建议限制某些类型。但是,您需要在服务器端代码中重新验证以确保。永远不要相信客户发给你的东西。

回答by Timmerz

more explicitly...

更明确...

<input type="file" accept="application/pdf" /> 

回答by Darin Dimitrov

Simply put: you can't using the plain html and javascript. The closest you can get is to test the file extension using javascript before submitting the form and show some error message to the user if it is other than .pdf. You might need to use some client side solution such as Flash upload controls if you want to achieve this.

简单地说:你不能使用纯 html 和 javascript。你能得到的最接近的是在提交表单之前使用 javascript 测试文件扩展名,如果它不是.pdf. 如果您想实现这一点,您可能需要使用一些客户端解决方案,例如 Flash 上传控件。