1.不用HTML中的img標籤來下載圖片,經過XHR api來下載圖片:html
1 var xhr = new XMLHttpRequest(); 2 xhr.open('GET','/img/tooth-intro.jpg'); 3 xhr.responseType = 'blob'; //二進制文件 4 xhr.onload = function(){ 5 if(this.status === 200){ 6 var img = document.createElement('img'); 7 img.src = window.URL.createObjectURL(this.response); 8 img.onload = function(){ 9 //圖片加載完,釋放一個URL資源。 10 window.URL.revokeObjectURL(this.src); 11 } 12 document.body.appendChild(img); 13 } 14 } 15 xhr.send();
HXR知足不了流式數據的傳輸,可是仍是有其餘的辦法,並且仍是專門爲流式數據處理和設計的,如: Server-Sent Events、和WebSocket。web
2.Server-Sent Eventsapi
Server-Sent Events提供方便的流API,用於從服務器向客戶端發送文本數據,判斷瀏覽器是否支持SSE:瀏覽器
typeof(EventSource)!=="undefined" // true 支持;false 不支持。
客戶端:服務器
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>Basic SSE Example</title> </head> <body> <pre id="x">Initializing...</pre> <script> var es = new EventSource("sse"); es.addEventListener("message", function(e){ document.getElementById("x").innerHTML += "\n" + e.data; },false); </script> </body> </html>
服務器:app
var http = require("http"), fs = require("fs"); var port = 1234; http.createServer(function(request, response){ console.log("Client connected:" + request.url); if(request.url!="/sse"){ fs.readFile("web/basic_sse.html", function(err,file){ response.writeHead(200, { 'Content-Type': 'text/html' }); var s = file.toString(); //file is a buffer response.end(s); }); return; } //Below is to handle SSE request. It never returns. response.writeHead(200, { "Content-Type": "text/event-stream" }); var timer = setInterval(function(){ var content = "data:" + new Date().toISOString() + "\n\n"; var b = response.write(content); if(!b)console.log("Data got queued in memory (content=" + content + ")"); else console.log("Flushed! (content=" + content + ")"); },1000); request.connection.on("close", function(){ response.end(); clearInterval(timer); console.log("Client closed connection. Aborting."); }); }).listen(port); console.log("Server running at http://localhost:" + port);
而WebSocket則提供了高效、雙向的流機制,並且同時支持二進制和文件數據。ui