Skip to content

Commit

Permalink
Add example
Browse files Browse the repository at this point in the history
  • Loading branch information
teoli2003 committed Mar 30, 2023
1 parent 384c34e commit 6a03622
Show file tree
Hide file tree
Showing 13 changed files with 977 additions and 478 deletions.
Binary file not shown.
184 changes: 117 additions & 67 deletions files/en-us/web/api/xmlhttprequestupload/abort_event/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,95 +38,145 @@ _In addition to the properties listed below, properties from the parent interfac

## Examples

### Live example
### Uploading a file with a timeout

This allows you to upload a file to a server; it displays a progress bar while the upload is happening as well as a message with the progress and the results, success or failure. An abort button allows to stop an upload.

#### HTML

```html
<div class="controls">
<input
class="xhr success"
type="button"
name="xhr"
value="Click to start XHR (success)" />
<input
class="xhr error"
type="button"
name="xhr"
value="Click to start XHR (error)" />
<input
class="xhr abort"
type="button"
name="xhr"
value="Click to start XHR (abort)" />
</div>

<textarea readonly class="event-log"></textarea>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>XMLHttpRequestUpload test</title>
<link rel="stylesheet" href="xhrupload_test.css" />
<script src="xhrupload_test.js"></script>
</head>
<body>
<main>
<h1>Upload a file</h1>
<p>
<label for="file">File to upload</label><input type="file" id="file" />
</p>
<p>
<progress />
</p>
<p>
<output></output>
</p>
<p>
<button disabled id="abort">Abort</button>
</p>
</main>
</body>
</html>
```

```css hidden
.event-log {
width: 25rem;
height: 4rem;
border: 1px solid black;
margin: 0.5rem;
padding: 0.2rem;
}
#### CSS

input {
width: 11rem;
margin: 0.5rem;
```css
body {
background-color: lightblue;
}
```

#### JavaScript

```js
const xhrButtonSuccess = document.querySelector('.xhr.success');
const xhrButtonError = document.querySelector('.xhr.error');
const xhrButtonAbort = document.querySelector('.xhr.abort');
const log = document.querySelector('.event-log');
main {
margin: 50px auto;
text-align: center;
}

function handleEvent(e) {
log.textContent = `${log.textContent}${e.type}: ${e.loaded} bytes transferred\n`;
#file {
display: none;
}

function addListeners(xhr) {
xhr.addEventListener('loadstart', handleEvent);
xhr.addEventListener('load', handleEvent);
xhr.addEventListener('loadend', handleEvent);
xhr.addEventListener('progress', handleEvent);
xhr.addEventListener('error', handleEvent);
xhr.addEventListener('abort', handleEvent);
label[for="file"] {
background-color: lightgrey;
padding: 10px 10px;
}

function runXHR(url) {
log.textContent = '';
progress {
display: none;
}

const xhr = new XMLHttpRequest();
addListeners(xhr);
xhr.open("GET", url);
xhr.send();
return xhr;
progress.visible {
display: inline;
}
```

xhrButtonSuccess.addEventListener('click', () => {
runXHR('dgszyjnxcaipwzy.jpg');
});
#### JavaScript

xhrButtonError.addEventListener('click', () => {
runXHR('https://somewhere.org/i-dont-exist');
});
```js
addEventListener("DOMContentLoaded", () => {
const fileInput = document.getElementById("file");
const progressBar = document.querySelector("progress");
const log = document.querySelector("output");
const abortButton = document.getElementById("abort");

xhrButtonAbort.addEventListener('click', () => {
runXHR('dgszyjnxcaipwzy.jpg').abort();
fileInput.addEventListener("change", () => {
const xhr = new XMLHttpRequest();
xhr.timeout = 2000; // 2 seconds

// Link abort button
abortButton.addEventListener(
"click",
() => {
xhr.abort();
},
{ once: true }
);

// When the upload starts, we display the progress bar
xhr.upload.addEventListener("loadstart", (event) => {
progressBar.classList.add("visible");
progressBar.value = 0;
progressBar.max = event.total;
log.textContent = "Uploading (0%)…";
abortButton.disabled = false;
});

// Each time a progress event is received we update the bar
xhr.upload.addEventListener("progress", (event) => {
progressBar.value = event.loaded;
log.textContent = `Uploading (${(
(event.loaded / event.total) *
100
).toFixed(2)}%)…`;
});

// When the upload is finished, we hide the progress bar.
xhr.upload.addEventListener("loadend", (event) => {
progressBar.classList.remove("visible");
if (event.loaded !== 0) {
log.textContent = "Upload finished.";
}
abortButton.disabled = true;
});

// In case of an error, an abort, or a timeout, we hide the progress bar
// Note that these events can be listened to on the xhr object too
function errorAction(event) {
progressBar.classList.remove("visible");
log.textContent = `Upload failed: ${event.type}`;
}
xhr.upload.addEventListener("error", errorAction);
xhr.upload.addEventListener("abort", errorAction);
xhr.upload.addEventListener("timeout", errorAction);

// Build the payload
const fileData = new FormData();
fileData.append("file", fileInput.files[0]);

// Theoretically, event listeners could be set after the open() call
// but browsers are buggy here
xhr.open("POST", "upload_test.php", true);

// Note that the event listener must be set before sending (as it is a preflighted request)
xhr.send(fileData);
});
});
```

#### Result

{{ EmbedLiveSample('Live_example', '100%', '150px') }}

## Specifications

{{Specifications}}
Expand Down
Binary file not shown.

0 comments on commit 6a03622

Please sign in to comment.