当前位置:Gxlcms > JavaScript > Ajax实现下载进度条的示例代码

Ajax实现下载进度条的示例代码

时间:2021-07-01 10:21:17 帮助过:28人阅读

本篇文章给大家带来的内容是关于Ajax实现下载进度条的示例代码,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

可以通过设置一个XMLHttpRequest对象的 responseType 属性来改变一个从服务器上返回的响应的数据类型。可用的属性值为空字符串 (默认), "arraybuffer", "blob", "document", 和 "text".

response 属性的值会根据 responseType 属性的值的不同而不同, 可能会是一个 ArrayBuffer, Blob, Document, string,或者为NULL(如果请求未完成或失败)。

新版本的 XMLHttpRequest 对象,传送数据的时候,有一个 progress 事件,用来返回进度信息。

它分成 上传 和 下载 两种情况。下载的 progress 事件属于 XMLHttpRequest 对象,上传的 progres s事件属于 XMLHttpRequest.upload 对象。

1、前端代码:

  1. downLoadProcess(url,filename){
  2. filename = filename || 'xxx.csv';
  3. // 创建xhr对象
  4. var req = new XMLHttpRequest();
  5. //向服务器发送请求 open() send()
  6. req.open("POST", url, true); //(method-GET/POST ,url, async)
  7. req.setRequestHeader("Content-type","application/x-www-form-urlencoded");//POST时需要传递
  8. //监听进度事件
  9. xhr.addEventListener("progress", uploadProgress, false);
  10. xhr.addEventListener("load", uploadComplete, false);
  11. xhr.addEventListener("error", uploadFailed, false);
  12. xhr.addEventListener("abort", uploadCanceled, false);
  13. /*
  14. XMLHttpRequest 的 responseType 属性
  15. 一个枚举类型的属性,返回响应数据的类型,只能设置异步的请求
  16. 1、'' -- DOMString (默认); UTF-16
  17. 2、arraybuffer -- arraybuffer对象,即类型化数组
  18. 3、blob -- Blob对象, 二进制大数据对象
  19. 4、document -- Document对象
  20. 5、json
  21. 6、text
  22. */
  23. //设置返回数据的类型
  24. req.responseType = "blob";
  25. req.onreadystatechange = function () { //同步的请求无需onreadystatechange
  26. if (req.readyState === 4 && req.status === 200) {
  27. var filename = $(that).data('filename');
  28. if (typeof window.chrome !== 'undefined') {
  29. // Chrome version
  30. var link = document.createElement('a');
  31. link.href = window.URL.createObjectURL(req.response);
  32. link.download = filename;
  33. link.click();
  34. } else if (typeof window.navigator.msSaveBlob !== 'undefined') {
  35. // IE version
  36. var blob = new Blob([req.response], { type: 'application/force-download' });
  37. window.navigator.msSaveBlob(blob, filename);
  38. } else {
  39. // Firefox version
  40. var file = new File([req.response], filename, { type: 'application/force-download' });
  41. window.open(URL.createObjectURL(file));
  42. }
  43. }
  44. };
  45. req.send("fname=Henry&lname=Ford");
  46. }
  47. function uploadProgress(evt) {
  48. if (evt.lengthComputable) {          /*后端的主要时间消耗都在查询数据和生成文件,所以可以设置默认值,直到真正到达下载的进度,再开始走进度条*/
  49. var percent = Math.round(evt.loaded * 100 / evt.total);
  50. document.getElementById('progress').innerHTML = percent.toFixed(2) + '%';
  51. document.getElementById('progress').style.width = percent.toFixed(2) + '%';
  52. }else {
  53. document.getElementById('progress').innerHTML = 'unable to compute';
  54. }
  55. }
  56. function uploadComplete(evt) {
  57. /* 服务器端返回响应时候触发event事件*/
  58. document.getElementById('result').innerHTML = evt.target.responseText;
  59. }
  60. function uploadFailed(evt) {
  61. alert("There was an error attempting to upload the file.");
  62. }
  63. function uploadCanceled(evt) {
  64. alert("The upload has been canceled by the user or the browser dropped the connection.");
  65. }

2、后台处理接口

  1. public void aaa()
  2. {
  3. string result = string.Empty;
  4. for (int i = 1; i <= 6000; i++)
  5. {
  6. result += i.ToString();
  7. int len = result.Length;
  8. Response.Headers.Add("Content-Length", len.ToString());
  9. Response.Headers.Add("Content-Encoding", "UTF-8");
  10. Response.Write(result);
  11. }
  12. }

注意到 ::

Response.Headers.Add("Content-Length", len.ToString());
Response.Headers.Add("Content-Encoding", "UTF-8");

写出 http 头时候,附加 “Content-Length”和Content-Encoding,

这样 JS 端的 progress 事件的 event.lengthComputable 值才会为 true, event.total 才会在数据传输完毕之前取得值,

否则 event.lengthComputable 值会返回 false, event.total 在数据完成之前值都是0。

本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注PHP中文网的JavaScript教程视频栏目!

以上就是Ajax实现下载进度条的示例代码的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行