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

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

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

 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,一般是由于服务器没有设置数据包的长度导致的。因此,在服务器端回传的代码片段如下:

 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即是下载文件的总长度

参考资料:

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

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

猜你喜欢

转载自www.cnblogs.com/webbery/p/10486750.html