使用jquery给网站添加下载进度显示

由于一块儿读论文网站的流出带宽特别低,为了给用户更好的体验,在线打开pdf的时候,考虑采用两条途径:一条是按页提供给用户进行阅读,减小带宽占用,由于不是全部的用户都所有页面都看一遍;另外一条是给出pdf的下载进度提示,用户可以有交互式的感知体验。第一条限于技术缘由,实现起来较为复杂;所以先实现了第二条途径。前端

从网站的技术角度来看,前端页面对服务器发出ajax请求,服务器收到请求后读取对应pdf,经过Nodejs的Stream方式回传给页面。下面的代码显示了经过jquery发送ajax请求,并在控制台显示进度信息jquery

 1 $.ajax({  2             url: '/api/version',  3             type: 'post',  4             dataType: 'json',  5  data: { paperid: paperid, version: filename },  6  statusCode: {  7                 200: function (json) {},  8  },  9             xhr: function(){ 10                 var xhr = new window.XMLHttpRequest(); 11                 //download progress
12                 xhr.addEventListener("progress", function (evt) { 13                     if (evt.lengthComputable) { 14                         var percentComplete = evt.loaded / evt.total; 15                         console.info("progress: "+Math.round(percentComplete * 100)+"%"); 16  } 17                 }, false); 18                 return xhr; 19  } 20         });

若是evt.lengthComputable为false,通常是因为服务器没有设置数据包的长度致使的。所以,在服务器端回传的代码片断以下:ajax

 1         const s = new Readable();  2  s.push(blob);  3         s.push(null);  4  res.set({  5             'Accept-Ranges':'bytes',  6             'Content-Type': 'application/octet-stream',  7             'Content-Disposition': 'attachment; filename=' + paperid + '.pdf',  8             'Content-Length': blob.length  9  }); 10         s.pipe(res);
Content-Length便是下载文件的总长度

参考资料:json

http://api.jquery.com/jQuery.ajax/api

https://stackoverflow.com/questions/22502943/jquery-ajax-progress-via-xhr服务器

相关文章
相关标签/搜索