<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-CN" dir="ltr">
<head>
</head>
<body>
<input type="file" id="file" > <!-- 只能上傳單個文件 -->
<input type="file" id="files" multiple> <!-- 可以上傳多個文件 -->
<input type="file" accept="image/*"/> 設置上傳文件類型,這樣打開文件的時候會只出現符合該類型的文件。
或者列出詳細的類型如:<input type="file" accept="image/x-png,image/gif,image/jpeg,image/bmp" />
<script>
window.onload=function(){
var f = document.getElementById("file");
var fs = document.getElementById("files");
//this.files即獲取input中上傳的file對象 是個數組
f.onchange = function(){
//獲取文件對象
var file = this.files[0];
//使用fileReader對文件對象進行操作
var reader = new FileReader();
//將文件讀取為arrayBuffer
//reader.readAsArrayBuffer(file);
//reader.onload = function(){
// console.log(reader.result);
//}
/*reader.readAsBinaryString(file);
reader.onload = function(){
console.log(reader.result);
}
*/
//用於圖片顯示不需要傳入后台,reader.result的結果是base64編碼數據,直接放入img的src中即可
reader.readAsDataURL(file);
reader.onload = function(){
console.log(reader.result);
}
}
fs.onchange = function(){
}
}
</script>
</body>
</html>
Valid Accept Types: For CSV files (.csv), use: <input type="file" accept=".csv" /> For Excel Files 2003-2007 (.xls), use: <input type="file" accept="application/vnd.ms-excel" /> For Excel Files 2010 (.xlsx), use: <input type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" /> For Text Files (.txt) use: <input type="file" accept="text/plain" /> For Image Files (.png/.jpg/etc), use: <input type="file" accept="image/*" /> For HTML Files (.htm,.html), use: <input type="file" accept="text/html" /> For Video Files (.avi, .mpg, .mpeg, .mp4), use: <input type="file" accept="video/*" /> For Audio Files (.mp3, .wav, etc), use: <input type="file" accept="audio/*" /> For PDF Files, use: <input type="file" accept=".pdf" />
有個缺點,在設置后瀏覽器打開選擇文件窗口時會自動篩選的文件夾下所有符合設定類型的文件,造成文件窗口延遲一定時間。
優化的方法是列出你需要的詳細類型,比如:
For Image Files (.png/.jpg/etc), use: <input type="file" accept="image/x-png,image/gif,image/jpeg,image/bmp" />
這樣打開的速度就快很多了
