<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
檔案上傳:<input type="file" /> (IE9及以下不支援下面這些功能,其它瀏覽器最新版本均已支援。)
允許選擇多個檔案:
<input type="file" multiple>
只允許上傳一個檔案:
<input type="file" single>
<input type="file" accept="image/gif,image/png" />
這裡的上傳格式僅指開啟上傳彈窗選擇檔案時預設的檔案格式,可手動修改成其它檔案格式。
如果不限制上傳圖片的格式可寫成:accept="image/*"
其它格式參考如下:
*.3gpp audio/3gpp, video/3gpp 3GPP Audio/Video
*.ac3 audio/ac3 AC3 Audio
*.asf allpication/vnd.ms-asf Advanced Streaming Format
*.au audio/basic AU Audio
*.css text/css Cascading Style Sheets
*.csv text/csv Comma Separated Values
*.doc application/msword MS Word Document
*.dot application/msword MS Word Template
*.dtd application/xml-dtd Document Type Definition
*.dwg image/vnd.dwg AutoCAD Drawing Database
*.dxf image/vnd.dxf AutoCAD Drawing Interchange Format
*.gif image/gif Graphic Interchange Format
*.htm text/html HyperText Markup Language
*.html text/html HyperText Markup Language
*.jp2 image/jp2 JPEG-2000
*.jpe image/jpeg JPEG
*.jpeg image/jpeg JPEG
*.jpg image/jpeg JPEG
*.js text/javascript, application/javascript JavaScript
*.json application/json JavaScript Object Notation
*.mp2 audio/mpeg, video/mpeg MPEG Audio/Video Stream, Layer II
*.mp3 audio/mpeg MPEG Audio Stream, Layer III
*.mp4 audio/mp4, video/mp4 MPEG-4 Audio/Video
*.mpeg video/mpeg MPEG Video Stream, Layer II
*.mpg video/mpeg MPEG Video Stream, Layer II
*.mpp application/vnd.ms-project MS Project Project
*.ogg application/ogg, audio/ogg Ogg Vorbis
*.pdf application/pdf Portable Document Format
*.png image/png Portable Network Graphics
*.pot application/vnd.ms-powerpoint MS PowerPoint Template
*.pps application/vnd.ms-powerpoint MS PowerPoint Slideshow
*.ppt application/vnd.ms-powerpoint MS PowerPoint Presentation
*.rtf application/rtf, text/rtf Rich Text Format
*.svf image/vnd.svf Simple Vector Format
*.tif image/tiff Tagged Image Format File
*.tiff image/tiff Tagged Image Format File
*.txt text/plain Plain Text
*.wdb application/vnd.ms-works MS Works Database
*.wps application/vnd.ms-works Works Text Document
*.xhtml application/xhtml+xml Extensible HyperText Markup Language
*.xlc application/vnd.ms-excel MS Excel Chart
*.xlm application/vnd.ms-excel MS Excel Macro
*.xls application/vnd.ms-excel MS Excel Spreadsheet
*.xlt application/vnd.ms-excel MS Excel Template
*.xlw application/vnd.ms-excel MS Excel Workspace
*.xml text/xml, application/xml Extensible Markup Language
*.zip aplication/zip Compressed Archive
FileList物件都是一組檔案物件的集合,而檔案物件則擁有下列的屬性:
name – 檔名(不包含路徑)
type – 檔案的MIME型別(小寫)
size – 檔案的尺寸(單位為位元組)
lastModifiedDate 為上傳檔案的最後修改時間
通過上面的幾個物件,我們能夠控制使用者上傳的檔案大小和檔案型別,以便減輕伺服器再次檢測時的壓力,並提升安全係數
var a=document.getElementById("file"); a.onchange=function(e){ e=e || window.event; var b=e.target.files; alert(b[0].name); }
dataTransfer 物件
dropEffect[=sCursorStyle]
設定或獲取拖拽操作的型別和要顯示的遊標型別
effectAllowed[=sEffect]
設定或獲取資料傳送操作可應用與該物件的源元素
setData(sFormat,sData)
將指定格式的資料賦值給dataTransfer或者clipboardData sFormat:URL,TextgetData(sFormat)
從dataTransfer或者clipboardData中獲取值 sFormat:URL,TextclearData([sFormat])
通過dataTransfer或者clipboardData中刪除某種格式的資料 sFormat:Text,URL,File,HTML,Image
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> #DropZone{border:1px solid #CCC;height:50px;} </style> </head> <body> <input type="file" multiple accept="image/gif,image/png" id="file"> <div id="DropZone"></div> <div id="Lists"></div> <script> var aa=document.getElementById("file"); aa.onchange=function(){ fileDrop(); } function fileDrop(e) { e = e || window.event; e.stopPropagation(); // 阻止冒泡 e.preventDefault(); //阻止預設行為 var files = e.dataTransfer.files; //FileList var output = []; for(var i = 0, f; f = files[i]; i++) { output.push('<li><strong>' + f.name + '</strong>(' + f.type + ') - ' + f.size +' bytes</li>'); } document.getElementById('Lists').innerHTML = '<ul>' + output.join('') + '</ul>'; }; function dragOver(e) { e = e || window.event; e.stopPropagation(); e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; //指定拖放視覺效果 }; var d = document.getElementById('DropZone'); try { d.addEventListener('dragover', dragOver, false); d.addEventListener('drop', fileDrop, false) } catch(ex) { document.write('something must be wrong!'); } </script> </body> </html>
FileReader包含四種非同步讀取檔案的方式:
一旦這些read方法被呼叫,onloadstart, onprogress, onload, onabort, onerror, onloadend就可以被用來追蹤進度。
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> body{margin:0;padding:0;} img{vertical-align:bottom;} </style> </head> <body> <input type="file" multiple accept="image/gif,image/png,,image/jpeg" id="Files"> <div id="Preview"></div> <ul id="Errors"></ul> <script> function fileSelect(e) { e = e || window.event; var files = e.target.files; //FileList Objects var ireg = /image/.*/i, p = document.getElementById('Preview'); var ul = document.getElementById('Errors'); for(var i = 0, f; f = files[i]; i++) { if(!f.type.match(ireg)) { //設定錯誤資訊 var li = document.createElement('li'); li.innerHTML = '<li>' + f.name +'不是圖片檔案.</li>'; ul.appendChild(li); continue; } var reader = new FileReader(); reader.onload = (function(file) { return function(e) { var span = document.createElement('span'); var img = new Image; img.alt=file.name; img.onload = function() { console.log(img.height); // image is loaded; sizes are available }; img.src=this.result; span.innerHTML = '<img class="thumb" src="'+ this.result +'" alt="'+ file.name +'" />'; p.insertBefore(span, null); }; })(f); //讀取檔案內容 reader.readAsDataURL(f); } } if(window.File && window.FileList && window.FileReader && window.Blob) { document.getElementById('Files').addEventListener('change', fileSelect, false); } else { document.write('您的瀏覽器不支援File Api'); } </script> </body> </html>
上傳txt檔案內容預覽(需對<>&'"|等符號進行過濾否則會中斷讀取):
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> body{margin:0;padding:0;} img{vertical-align:bottom;} </style> </head> <body> <input type="file" multiple id="Files"> <div id="Preview"></div> <ul id="Errors"></ul> <script> function encodeHTML(source) { //return source; return source .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"'); }; function fileSelect(e) { e = e || window.event; var files = e.target.files; //FileList Objects var ireg = /text/.*/i, p = document.getElementById('Preview'); var ul = document.getElementById('Errors'); for(var i = 0, f; f = files[i]; i++) { console.log(f.type); if(!f.type.match(ireg)) { //設定錯誤資訊 var li = document.createElement('li'); li.innerHTML = '<li>' + f.name +'不是文字檔案.</li>'; ul.appendChild(li); continue; } var reader = new FileReader(); reader.onload = (function(file) { return function(e) { var div = document.createElement('div'); div.className = "text" div.innerHTML = encodeHTML(this.result); p.insertBefore(div, null); }; })(f); //讀取檔案內容 reader.readAsText(f); } } if(window.File && window.FileList && window.FileReader && window.Blob) { document.getElementById('Files').addEventListener('change', fileSelect, false); } else { document.write('您的瀏覽器不支援File Api'); } </script> </body> </html>
讀取上傳txt指定區域文字內容:
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> body{margin:0;padding:0;} img{vertical-align:bottom;} </style> </head> <body> <input type="file" multiple id="Files"> <button type="button" id="buttons" data-start="0" data-end="3">確定</button> <div id="range"></div> <div id="content"></div> <script> function readBlob(start, end) { var files = document.getElementById('Files').files; if(!files.length) { alert('請選擇檔案'); return false; } var file = files[0], start = parseInt(start, 10) || 0, end = parseInt(end, 10) || (file.size - 1); var r = document.getElementById('range'), c = document.getElementById('content'); var reader = new FileReader(); reader.onloadend = function(e) { if(this.readyState == FileReader.DONE) { c.textContent = this.result; r.textContent = "Read bytes: " + (start + 1) + " - " + (end + 1) + " of " + file.size + " bytes"; } }; var blob; blob = file.slice(start, end + 1, 'text/plain;charset=UTF-8'); reader.readAsBinaryString(blob); }; try { document.getElementById('buttons').addEventListener('click', function(e) { if(e.target.tagName.toLowerCase() == 'button') { var start = e.target.getAttribute('data-start'), end = e.target.getAttribute('data-end'); readBlob(start, end); } }); } catch(ex) { alert('something error happens!') } </script> </body> </html>
File介面提供了slice方法支援把檔案切成不同的片段,第一個引數是起始的位元組數,第二個引數是結束的位元組數,還有一個可選的內容型別字串可以作為第三個引數。早期的chrome和firefox版本不支援file.slice 可使用file.webkitSlice和file.mozSlice替代,最新版本均支援file.slice。
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <form> <fieldset> <legend>分度讀取檔案:</legend> <input type="file" id="File" /> <input type="button" value="中斷" id="Abort" /> <p> <label>讀取進度:</label><progress id="Progress" value="0" max="100"></progress> </p> <p id="Status"></p> </fieldset> </form> <script> var h = { init: function() { var me = this; document.getElementById('File').onchange = me.fileHandler; document.getElementById('Abort').onclick = me.abortHandler; me.status = document.getElementById('Status'); me.progress = document.getElementById('Progress'); me.percent = document.getElementById('Percent'); me.loaded = 0; //每次讀取1M me.step = 1024 * 1024; me.times = 0; }, fileHandler: function(e) { var me = h; var file = me.file = this.files[0]; var reader = me.reader = new FileReader(); // me.total = file.size; reader.onloadstart = me.onLoadStart; reader.onprogress = me.onProgress; reader.onabort = me.onAbort; reader.onerror = me.onerror; reader.onload = me.onLoad; reader.onloadend = me.onLoadEnd; //讀取第一塊 me.readBlob(file, 0); }, onLoadStart: function() { var me = h; }, onProgress: function(e) { var me = h; me.loaded += e.loaded; //更新進度條 me.progress.value = (me.loaded / me.total) * 100; }, onAbort: function() { var me = h; }, onError: function() { var me = h; }, onLoad: function() { var me = h; if(me.loaded < me.total) { me.readBlob(me.loaded); } else { me.loaded = me.total; } }, onLoadEnd: function() { var me = h; }, readBlob: function(start) { var me = h; var blob, file = me.file; me.times += 1; if(file.slice) { blob = file.slice(start, start + me.step + 1); } else if(file.mozSlice) { blob = file.mozSlice(start, start + me.step + 1); } me.reader.readAsText(blob); }, abortHandler: function() { var me = h; if(me.reader) { me.reader.abort(); } } }; h.init(); </script> </body> </html>
本文程式碼以chrome測試為主。
到此這篇關於JavaScript檔案上傳問題整理的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支援it145.com。
相關文章
<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
综合看Anker超能充系列的性价比很高,并且与不仅和iPhone12/苹果<em>Mac</em>Book很配,而且适合多设备充电需求的日常使用或差旅场景,不管是安卓还是Switch同样也能用得上它,希望这次分享能给准备购入充电器的小伙伴们有所
2021-06-01 09:31:42
除了L4WUDU与吴亦凡已经多次共事,成为了明面上的厂牌成员,吴亦凡还曾带领20XXCLUB全队参加2020年的一场音乐节,这也是20XXCLUB首次全员合照,王嗣尧Turbo、陈彦希Regi、<em>Mac</em> Ova Seas、林渝植等人全部出场。然而让
2021-06-01 09:31:34
目前应用IPFS的机构:1 谷歌<em>浏览器</em>支持IPFS分布式协议 2 万维网 (历史档案博物馆)数据库 3 火狐<em>浏览器</em>支持 IPFS分布式协议 4 EOS 等数字货币数据存储 5 美国国会图书馆,历史资料永久保存在 IPFS 6 加
2021-06-01 09:31:24
开拓者的车机是兼容苹果和<em>安卓</em>,虽然我不怎么用,但确实兼顾了我家人的很多需求:副驾的门板还配有解锁开关,有的时候老婆开车,下车的时候偶尔会忘记解锁,我在副驾驶可以自己开门:第二排设计很好,不仅配置了一个很大的
2021-06-01 09:30:48
不仅是<em>安卓</em>手机,苹果手机的降价力度也是前所未有了,iPhone12也“跳水价”了,发布价是6799元,如今已经跌至5308元,降价幅度超过1400元,最新定价确认了。iPhone12是苹果首款5G手机,同时也是全球首款5nm芯片的智能机,它
2021-06-01 09:30:45