forked from edspencer/Ext.ux.Exporter
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathFileSaver.js
83 lines (83 loc) · 3.34 KB
/
FileSaver.js
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
/**
* @Class Ext.ux.exporter.FileSaver
* @author Yogesh
* Class that allows saving file via blobs: URIs or data: URIs or download remotely from server
*/
Ext.define('Ext.ux.exporter.FileSaver', {
statics: {
saveAs: function(data, mimeType, charset, filename, link, remote, cb, scope) {
window.URL = window.URL || window.webkitURL;
try { //If browser supports Blob(Gecko,Chrome,IE10+)
var blob = new Blob([data], { //safari 5 throws error
type: mimeType + ";charset=" + charset + ","
});
if (link && "download" in link) {
blobURL = window.URL.createObjectURL(blob);
link.href = blobURL;
link.download = filename;
if(cb) cb.call(scope);
this.cleanBlobURL(blobURL);
return;
} else if (window.navigator.msSaveOrOpenBlob) { //IE 10+
window.navigator.msSaveOrOpenBlob(blob, filename);
if(cb) cb.call(scope);
return;
}
} catch (e) { //open using data:URI
Ext.log("Browser doesn't support Blob: " + e.message);
}
//Browser doesn't support Blob save
if(remote) {//send data to sever to download
this.downloadUsingServer(data, mimeType, charset, filename, cb, scope);
} else{//open data in new window
this.openUsingDataURI(data, mimeType, charset);
if(cb) cb.call(scope);
}
},
downloadUsingServer: function(data, mimeType, charset, filename, cb, scope) {
var form = Ext.getDom('formDummy');
if(!form) {
form = document.createElement('form');
form.id = 'formDummy';
form.name = 'formDummy';
form.className = 'x-hidden';
document.body.appendChild(form);
}
Ext.Ajax.request({
url: '/ExportFileAction',
method: 'POST',
form: form,
isUpload: true,
params: {
userAction: 'download',
data: data,
mimeType: mimeType,
charset: charset,
filename: filename
},
callback: function() {
if(cb) cb.call(scope);
}
});
},
openUsingDataURI: function(data, mimeType, charset) {
if (Ext.isIE9m) { //for IE 9 or lesser
w = window.open();
doc = w.document;
doc.open(mimeType, 'replace');
doc.charset = charset;
doc.write(data);
doc.close();
doc.execCommand("SaveAs", null, filename);
} else {
window.open("data:" + mimeType + ";charset=" + charset + "," + encodeURIComponent(data), "_blank");
}
},
cleanBlobURL: function(blobURL) {
// Need a some delay for the revokeObjectURL to work properly.
setTimeout(function() {
window.URL.revokeObjectURL(blobURL);
}, 10000);
}
}
});