我用了 <input type= "file" name="Upload" >
现在我想通过只接受.pdf和.xls文件来限制它.
当我单击提交按钮时,它应该验证这一点.
当我点击网页上的文件(PDF/XLS)时,它应该会自动打开.
有人可以举一些例子吗?
fee*_*ela 147
您可以通过使用该属性accept并向其添加允许的mime类型来实现.但并非所有浏览器都尊重该属性,并且可以通过某些代码检查器轻松删除它.因此,在任何一种情况下,您都需要检查服务器端的文件类型(第二个问题).
例:
<input type="file" name="upload" accept="application/pdf,application/vnd.ms-excel" />
Run Code Online (Sandbox Code Playgroud)
至于你的第三个问题"当我点击网页上的文件(PDF/XLS)时,它会自动打开.":
你无法做到这一点.如何在客户端计算机上打开PDF或XLS由用户设置.
Rad*_*dez 35
你可以用这个:
HTML
<input name="userfile" type="file" accept="application/pdf, application/vnd.ms-excel" />
Run Code Online (Sandbox Code Playgroud)
仅支持.PDF和.XLS文件
Joe*_*e C 11
不幸的是,在选择时没有保证的方法.
某些浏览器支持标记的accept属性input.这是一个良好的开端,但不能完全依赖.
Run Code Online (Sandbox Code Playgroud)<input type="file" name="pic" id="pic" accept="image/gif, image/jpeg" />
您可以使用a cfinput并运行验证来检查提交时的文件扩展名,但不能检查mime类型.这样更好,但仍然不是万无一失.OSX上的文件通常没有文件扩展名,或者用户可能恶意错误地标记文件类型.
ColdFusion cffile可以使用contentTyperesult(cffile.contentType)的属性检查mime-type ,但这只能在上传后完成.这是你最好的选择,但仍然不是100%安全,因为mime类型可能仍然是错误的.
小智 9
您可以尝试以下方式
<input type= "file" name="Upload" accept = "application/pdf,.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel">
Run Code Online (Sandbox Code Playgroud)
或(在 asp.net mvc 中)
@Html.TextBoxFor(x => x.FileName, new { @id = "doc", @type = "file", @accept = "application/pdf,.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" })
Run Code Online (Sandbox Code Playgroud)
你可以使用 JavaScript。考虑到使用 JavaScript 执行此操作的大问题是重置输入文件。好吧,这仅限于 JPG(对于 PDF,您必须更改mime 类型和幻数):
<form id="form-id">
<input type="file" id="input-id" accept="image/jpeg"/>
</form>
<script type="text/javascript">
$(function(){
$("#input-id").on('change', function(event) {
var file = event.target.files[0];
if(file.size>=2*1024*1024) {
alert("JPG images of maximum 2MB");
$("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
return;
}
if(!file.type.match('image/jp.*')) {
alert("only JPG images");
$("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
return;
}
var fileReader = new FileReader();
fileReader.onload = function(e) {
var int32View = new Uint8Array(e.target.result);
//verify the magic number
// for JPG is 0xFF 0xD8 0xFF 0xE0 (see https://en.wikipedia.org/wiki/List_of_file_signatures)
if(int32View.length>4 && int32View[0]==0xFF && int32View[1]==0xD8 && int32View[2]==0xFF && int32View[3]==0xE0) {
alert("ok!");
} else {
alert("only valid JPG images");
$("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
return;
}
};
fileReader.readAsArrayBuffer(file);
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
考虑到这是在最新版本的 Firefox 和 Chrome 以及 IExplore 10 上测试过的。
有关 mime 类型的完整列表,请参阅 Wikipedia。
| 归档时间: |
|
| 查看次数: |
181607 次 |
| 最近记录: |