经过XHR API来下载和上传图片

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

相关文章
相关标签/搜索