-
-
Notifications
You must be signed in to change notification settings - Fork 571
Expand file tree
/
Copy pathcsv_download_button_controller.js
More file actions
55 lines (47 loc) · 1.56 KB
/
csv_download_button_controller.js
File metadata and controls
55 lines (47 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
connect() {
this.element.addEventListener("click", this.handleClick.bind(this));
}
handleClick(event) {
event.preventDefault();
if (this.element.disabled) return;
this.element.disabled = true;
this.originalButtonText = this.element.textContent;
this.element.textContent = "Please wait...";
let filename = "export";
const url = this.element.href
fetch(url, { headers: { Accept: "text/csv" } })
.then(response => {
const contentType = response.headers.get("content-type");
if (!response.ok) {
throw new Error(`HTTP error. Status: ${response.status}`);
}
if (!contentType.includes("text/csv")) {
throw new Error(`Unexpected content type: ${contentType}`);
}
if(this.extractFilename(response)) {
filename = this.extractFilename(response);
}
return response.blob();
})
.then(blob => {
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = filename;
a.click();
URL.revokeObjectURL(a.href);
})
.catch((error) => console.log(`CSV Download failed: ${error}`)
)
.finally(() => {
this.element.textContent = this.originalButtonText;
this.element.disabled = false;
})
}
extractFilename(response) {
const contentDisposition = response.headers.get("content-disposition");
const match = contentDisposition.match(/filename="([^"]*)"/);
return match ? match[1] : null;
}
}