HTML input-file 上传类型控制

HTML input-file 上传类型控制


input file 属性

accept

表示可以选择的文件MIME类型,多个MIME类型用英文逗号分开,常用的MIME类型见下表。

只能选择png和gif图片

<input id="fileId1" type="file" accept="image/png,image/gif" name="file" />

multiple

是否可以选择多个文件,多个文件时其value值为第一个文件的虚拟路径。

多文件上传

<input id="fileId2" type="file" multiple="multiple" name="file" />

常用MIME类型

后缀名MIME名称
*.3gpp audio/3gpp, video/3gpp
*.ac3 audio/ac3
*.asf allpication/vnd.ms-asf
*.au audio/basic
*.css text/css
*.csv text/csv
*.doc application/msword
*.dot application/msword
*.dtd application/xml-dtd
*.dwg image/vnd.dwg
*.dxf image/vnd.dxf
*.gif image/gif
*.htm text/html
*.pot application/vnd.ms-powerpoint
*.ppt application/vnd.ms-powerpoint
*.rtf application/rtf, text/rtf
*.svf image/vnd.svf
*.tiff image/tiff
*.xlc application/vnd.ms-excel
*.xlm application/vnd.ms-excel
*.xlw application/vnd.ms-excel
*.xml text/xml, application/xml
*.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

AJAX上传文件

ajax上传的时候,需要获得input:file选择的文件(可能为多个文件),获取其文件列表为:

 // input标签的files属性 
 document.querySelector("#fileId").files 
 // 返回的是一个文件列表数组

获得的文件列表,然后遍历插入到表单数据当中。即:

// 获得上传文件DOM对象 
var oFiles = document.querySelector("#fileId"); 
// 实例化一个表单数据对象 
var formData = new FormData(); 
// 遍历图片文件列表,插入到表单数据中 
for (var i = 0, file; file = oFiles[i]; i++) {     
    // 文件名称,文件对象     
    formData.append(file.name, file); 
}

获得表单数据之后,就可以用ajax的POST上传。

// 实例化一个AJAX对象
var xhr = new XMLHttpRequest();
xhr.onload = function() {
    alert("上传成功!");
}
xhr.open("POST", "upload.php", true);

// 发送表单数据
xhr.send(formData);

上传到服务器之后,获取到文件列表为:

Array
(
    [jpg_jpg] => Array
        (
            [name] => jpg.jpg
            [type] => image/jpeg
            [tmp_name] => D:\xampp\tmp\phpA595.tmp
            [error] => 0
            [size] => 133363
        )

    [png_png] => Array
        (
            [name] => png.png
            [type] => image/png
            [tmp_name] => D:\xampp\tmp\phpA5A6.tmp
            [error] => 0
            [size] => 1214628
        )

)

在服务端循环遍历这个数组就可以上传文件了。

posted @ 2016-12-05 15:23  贺佃伟  阅读(16634)  评论(0编辑  收藏  举报