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
)
)
在服務端循環遍歷這個數組就可以上傳文件了。