-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathajax-blob-downloader.html
85 lines (67 loc) · 1.9 KB
/
ajax-blob-downloader.html
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<link rel="import" href="../polymer/polymer.html">
<!--
Download blob from ajax request.
### 1) Add the downloader element.
```html
<ajax-blob-downloader
id="downloader"
default-file-name="checklist.txt">
</ajax-blob-downloader>`
```
### 2) Add the ajax element that request and receive the blob content.
```html
<iron-ajax
id="downloadAjax"
handle-as="blob"
loading="{{_downloading}}"
on-response="_onFileDownloaded"
on-error="_onFileFailed">
</iron-ajax>
```
### 3) Send it to ajax-blob-downloader element from download method.
```js
_onFileDownloaded(e) {
this.$.downloader.download(e.detail);
}
```
### 4) Open the file! :)
-->
<dom-module id="ajax-blob-downloader">
<style>
:host {
display: block;
}
</style>
<template>
<a id="downloadedFile" style="display: none" target="_blank"></a>
</template>
<script>
(function () {
'use strict';
Polymer({
is: 'ajax-blob-downloader',
properties: {
/**
* Default file name when the blob received doesn't contain the Content-Disposition header enabled in CORs configuration
*
* @attribute defaultFileName
* @type string
*/
defaultFileName: {
type: String,
value: 'file.txt'
}
},
download(responseDetail) {
let url = window.URL.createObjectURL(responseDetail.xhr.response);
let contentDisposition = responseDetail.xhr.getResponseHeader('Content-Disposition');
let fileName = !contentDisposition ? this.defaultFileName : new RegExp(/^attachment; filename=([a-zA-Z0-9._]+)$/)
.exec(contentDisposition)[1];
this.$.downloadedFile.setAttribute("href", url);
this.$.downloadedFile.setAttribute("download", fileName);
this.$.downloadedFile.click();
}
});
})();
</script>
</dom-module>