限制input file元素文件接收类型,可通过 accept 属性字段进行约束。
例如显示input file只接收PNG、GIF、JPG、JPEG、TIF图片格式,可通过以下代码完成。
<input type="file" accept="image/png,image/gif,image/jpg,image/jpeg,image/tif" />
文件类型类型对照如下:
图片类型
png image/png
jpg image/jpg
jpeg image/jpeg
tif image/tif
gif image/gif
svg image/svg+xml
ico image/x-icon
bmp image/bmp
其他类型
txt text/plain
doc application/msword
docx application/vnd.openxmlformats-officedocument.wordprocessingml.document
xls application/vnd.ms-excel
xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
pdf application/pdf
pptx application/vnd.openxmlformats-officedocument.presentationml.presentation
ppt application/vnd.ms-powerpoint
不确定类型
对于不确定类型可以通过js将该文件转化base64文件格式即可确定 accept 类型。
操作如下(以xmind文件格式为例):
首选选择temp.xmind文件,文件格式为xmind
在console可确定该文件base64的格式类型。
data:application/vnd.xmind.workbook;base64
JS与HTML代码如下:
<input type="file" onchange='fileChanged(this)' />
fileChanged = function(_this){
var file=_this.files[0];
_this.value = null;
var reader = new FileReader();
reader.onload = function (evt) {
console.log(evt.target.result);
});
};
reader.readAsDataURL(file);
}