| 64 | } |
| 65 | |
| 66 | class XHRExampleDownload extends React.Component { |
| 67 | state: Object = { |
| 68 | downloading: false, |
| 69 | // set by onreadystatechange |
| 70 | contentLength: 1, |
| 71 | responseLength: 0, |
| 72 | // set by onprogress |
| 73 | progressTotal: 1, |
| 74 | progressLoaded: 0, |
| 75 | |
| 76 | readystateHandler: false, |
| 77 | progressHandler: true, |
| 78 | arraybuffer: false, |
| 79 | }; |
| 80 | |
| 81 | xhr: ?XMLHttpRequest = null; |
| 82 | cancelled: boolean = false; |
| 83 | |
| 84 | _download = () => { |
| 85 | let xhr; |
| 86 | if (this.xhr) { |
| 87 | xhr = this.xhr; |
| 88 | xhr.abort(); |
| 89 | } else { |
| 90 | xhr = this.xhr = new XMLHttpRequest(); |
| 91 | } |
| 92 | |
| 93 | const onreadystatechange = () => { |
| 94 | if (xhr.readyState === xhr.HEADERS_RECEIVED) { |
| 95 | const contentLength = |
| 96 | parseInt(xhr.getResponseHeader('Content-Length'), 10); |
| 97 | this.setState({ |
| 98 | contentLength, |
| 99 | responseLength: 0, |
| 100 | }); |
| 101 | } else if (xhr.readyState === xhr.LOADING && xhr.response) { |
| 102 | this.setState({ |
| 103 | responseLength: xhr.response.length, |
| 104 | }); |
| 105 | } |
| 106 | }; |
| 107 | const onprogress = (event) => { |
| 108 | this.setState({ |
| 109 | progressTotal: event.total, |
| 110 | progressLoaded: event.loaded, |
| 111 | }); |
| 112 | }; |
| 113 | |
| 114 | if (this.state.readystateHandler) { |
| 115 | xhr.onreadystatechange = onreadystatechange; |
| 116 | } |
| 117 | if (this.state.progressHandler) { |
| 118 | xhr.onprogress = onprogress; |
| 119 | } |
| 120 | if (this.state.arraybuffer) { |
| 121 | xhr.responseType = 'arraybuffer'; |
| 122 | } |
| 123 | xhr.onload = () => { |
nothing calls this directly
no test coverage detected
searching dependent graphs…