`
//首先判斷你的瀏覽器是否支持FileReader接口:
if( typeof FileReader == "undefined" ){
alert( "您的瀏覽器不支持FileReader!" );
}else{
// do FileReader things
}react
`瀏覽器
讀取後臺返回的流文件並下載,若是狀態500表示過時 解析文本。
`
response.blob().then( blob => {
if(typeof FileReader === 'undefined'){
notification.open({
message:'您的瀏覽器不支持 FileReader,請升級瀏覽器',
icon: <Icon type="smile" style={{ color: '#108ee9' }} />
})
}
const reader = new FileReader();ide
reader.addEventListener("loadend", function() { const resu = JSON.parse(reader.result); if(resu.code == 500){ notification.open({ message:resu.msg, icon: <Icon type="smile" style={{ color: '#108ee9' }} /> }) }else{ downloadBlob(blob); } }); reader.readAsText(blob,'utf-8'); //下載 function downloadBlob(blob){ let blobUrl = window.URL.createObjectURL(blob); let a = document.createElement('a'); let filename = options.Name; a.href = blobUrl; a.download = filename; a.click(); window.URL.revokeObjectURL(blobUrl); } })
`this
API編碼
`
FileReader有四個方法,三個用來讀取文件,一個用來中斷讀取:code
方法:abort
參數:無
做用:中斷讀取接口
方法:readAsBinaryString
參數:file
做用:將文件讀取爲二進制碼(打印出來在頁面上是一堆亂碼,二進制麼!)事件
方法:readAsDataURL
參數:file
做用:將文件讀取爲DataURL(本例中用的就是這個方法,result就是文件的base64字符,DataURI)圖片
方法:readAsText
參數:file, [optional] in DOMString encoding(第二個參數是文本的編碼方式,默認UTF-8)
做用:將文件讀取爲文本(讀取的結果就是這個文本文件中的內容)utf-8
此外,FileReader還包含了一套完整的事件模型,用來捕獲讀取文件時的狀態:
事件:onabort
描述:讀取中斷時觸發
事件:onerror
描述:出錯時觸發
事件:onload
描述:文件讀取成功完成時觸發
事件:onloadend
描述:讀取完成時觸發,不論讀取成功仍是失敗
事件:onloadstart
描述:讀取開始時觸發
事件:onprogress
描述:讀取中
文件一旦被讀取,不論成功仍是失敗,
實例(var reader = new FileReader)的result屬性都會被填充。
若是讀取失敗,result的值就是null,
若是讀取成功,result的值就是讀取的結果。
`
上傳文件
`
在頁面結構裏,咱們須要給一個input用來上傳文件:
則在支持FileReader的瀏覽器裏就能夠這樣寫:
document.getElementById("File").addEventListener("change", readFile, false);
這是在監聽input的change事件,一旦選擇了文件,觸發了change事件,即刻調用readFile方法。
besides,若是是上傳圖片,
咱們在結構裏能夠再給一個img:用來放置上傳的圖片。
由此咱們也順便實現了在圖片發送以前即顯示在頁面上的功能。
如今定義這個關鍵的readFile方法:
function readFile(){
var file = this.files[0]; //input
if( file.size > 510241024 ){ //用size屬性判斷文件大小不能超過5M alert( "你上傳的文件太大了!" ) }else{ var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function(e){ var res = this.result; $("#Img").attr("src", res); } } } 注意,這裏的this.result是把文件轉換爲base64後的字符串, 若是是圖片,則賦值給img的src便可顯示。 `