3336dbb4d9e1b92915def0fd80fc1a77eecf46c0
[Pman.Core] / Pman.Download.js
1 //<script type="text/javascript">
2 /**
3 * @class Pman.Download
4 * Handles file downloads in a hidden frame, or new window.
5 * Usage:
6 <pre><code>
7 var t = new Pman.Download({
8     url: baseURL + '/Images/Download/0/myfile.jpg',
9     newWindow : false,
10     params: { .... },
11     doctype: 'pdf' 
12     success : function() {
13         Roo.MessageBox.alert("File has downloaded");
14     }
15 });
16
17 </code></pre>
18
19 * @constructor
20 * @param {Object} cfg   Configuration object.
21 * @cfg {String} url     Location to download from.
22 * @cfg {String} method     GET or POST (default GET), POST will create a form, and post that into the hidden frame.
23 * @cfg {Boolean} newWindow (optional) download to new window
24 * @cfg {String} doctype (optional) download PDF to new window
25 * @cfg {Boolean} limit (optional) limit for grid downloads.
26  
27  * @cfg {String} csvCols  - use '*' to override grid coluns
28  * @cfg {String} csvTitles - use '*' to override grid coluns
29
30  
31  
32 * @cfg {Function} success (optional) MAY fire on download completed (fails on attachments)..
33 * @cfg {Number} timeout (optional) in milliseconds before it gives up (default 30000 = 30s)
34 * @cfg {Roo.grid.Grid} grid (optional) if you want to just download a grid, (without renderers..)
35
36 */
37
38 Pman.Download = function(cfg)
39 {
40     
41    
42     
43     this.params = {};
44     
45     Roo.apply(this, cfg);
46      
47     if (this.grid) {
48         
49         this.buildFromGrid();
50         Roo.log(this);
51     }
52     
53     
54     if (this.newWindow && this.method == 'GET') {
55         // as ie seems buggy...
56         window.open( this.url + '?' + Roo.urlEncode(this.params || {}), '_blank');
57         return ; 
58         
59     }
60    
61     
62     
63     //this.submit = false;
64     //this.createCsvFrame();
65     
66     //var requested = 0;
67      
68     //Roo.EventManager.on( this.csvFrame, 'load', this.onLoad, this);
69     
70     
71     //--- simple method..
72     this.method = this.method || 'GET';
73     
74     if (this.method == 'GET' && !this.params) {
75         (function() {
76             
77             
78             this.createCsvFrame();
79             //Roo.EventManager.on( this.csvFrame, 'load', this.onLoad, this);
80             this.submit = true;
81             this.csvFrame.src = cfg.url;
82             //this.cleanup.defer(cfg.timeout || 30000,this);
83         }).defer(100, this);
84         
85        
86         return;
87     }
88     
89     
90     Roo.log("creating form?");
91     
92     this.form = new FormData();
93     /*
94     var b = Roo.get(document.body);
95     this.form = b.createChild({
96         tag: 'form',
97         method : this.method,
98         action : this.url,
99         target : this.newWindow ? '_new' : this.csvFrame.id,
100         enctype : 'multipart/form-data'
101     });
102     **/
103 //    
104 //    if(this.doctype == 'pdf'){
105 //        this.pdfEmbed = b.createChild({
106 //            tag: 'embed',
107 //            src : this.url,
108 //            pluginspage : 'http://www.adobe.com/products/acrobat/readstep2.html',
109 //            alt: this.doctype
110 //        });
111 //    }
112  
113     Roo.log(this.params);
114     for(var i in this.params) {
115         this.form.append(i, this.params[i]);
116         /*
117         var el = this.form.createChild( {
118             ns : 'html',
119             tag : 'input',
120             
121             type: 'hidden',
122             name : i,
123             value : this.params[i]
124         });
125         */
126         
127         
128     }
129     var req = new XMLHttpRequest();
130     xhr.responseType = 'blob';
131     req.open(this.method, this.url);
132     
133     var _t = this;
134     req.onload = function( ev )
135     {
136         if (req.status == 200) {
137             Roo.log(ev);
138             var headers = req.getAllResponseHeaders();
139             Roo.log(req.getAllResponseHeaders())
140             var blob = new Blob([this.response], {type: req.responseType });
141             
142             var a = document.createElement("a");
143             a.style = "display: none";
144             document.body.appendChild(a);
145             var url = window.URL.createObjectURL(blob);
146             a.href = url;
147             a.download = 'myFile.pdf';
148              a.click();
149             //release the reference to the file by revoking the Object URL
150             window.URL.revokeObjectURL(url);
151             
152             _t.success ? _t.success(ev) : '';
153         } else {
154             _t.failure ? _t.failure(ev) : '';
155         }
156         
157     }
158     
159     req.send(this.form);
160     /*
161     (function() {
162         this.submit = true;
163         this.form.dom.submit();
164         this.cleanup.defer(this.timeout || 30000,this);
165     }).defer(100, this);
166     */
167      
168  
169 }
170
171 Roo.apply(Pman.Download.prototype, {
172     
173     /**
174      * @type {HTMLIframe} the iframe to download into.
175      */
176      
177     csvFrame : false,
178     
179     // private
180     form : false,
181     
182     limit : 9999,
183     
184     newWindow : false,
185     
186     method : 'GET',
187     
188     success : false,
189     failure : false,
190     
191     // private..
192     //used by simple GET method.
193     createCsvFrame: function()
194     {
195         if (this.csvFrame) {
196             document.body.removeChild(this.csvFrame);
197         }
198             
199         var id = Roo.id();
200         this.csvFrame = document.createElement('iframe');
201         this.csvFrame.id = id;
202         this.csvFrame.name = id;
203         this.csvFrame.className = 'x-hidden';
204         //if(Roo.isIE){
205             this.csvFrame.src = Roo.SSL_SECURE_URL;
206         //}
207         document.body.appendChild(this.csvFrame);
208
209         if(Roo.isIE){
210             document.frames[id].name = id;
211         }
212         
213     },
214     /* not used as it didn't work..
215     onLoad : function()
216     {
217        // requested++; // second request is real one..
218        // if (requested < 2) {
219        //     return;
220         //} // n
221         Roo.log('onload?');
222         if (!this.submit) {
223             return false;
224         }
225         //return false;
226       
227         var frame = this.csvFrame;
228         var success  = true; 
229         try { 
230             var doc = Roo.isIE ? 
231                 frame.contentWindow.document : 
232                 (frame.contentDocument || window.frames[Pman.Download.csvFrame.id].document);
233             
234             
235             if(doc && doc.body && doc.body.innerHTML.length){
236               //  alert(doc.body.innerHTML);
237                   
238                 Roo.MessageBox.alert("Download Error", doc.body.innerHTML);
239                 success  = false;
240                 if (this.failure) {
241                     this.failure();
242                 }
243                 return true;
244             }
245             
246             Roo.log(doc.body.innerHTML);
247              
248         }
249         catch(e) {
250             Roo.log(e.toString());
251             Roo.log(e);
252         }
253         if (this.success) {
254             this.success();
255         }
256         // we can not actually do anything with the frame... as it may actually still be downloading..
257         return true;
258     
259         this.cleanup();
260         
261         // this will never fire.. see 
262         // http://www.atalasoft.com/cs/blogs/jake/archive/2009/08/18/events-to-expect-when-dynamically-loading-iframes-in-javascript-take-2-thanks-firefox-3-5.aspx
263         if (this.success && success) {
264             
265             this.success();
266         }
267         return false;
268         
269
270     },
271      */
272     // private - clean up download elements.
273     cleanup :function()
274     {
275        /* Roo.log('cleanup?');
276         if (this.form) {
277             this.form.remove();
278             this.form= false;
279         
280         }
281         
282         if (this.csvFrame) {
283             Roo.EventManager.removeListener(this.csvFrame, 'load', this.onLoad, this);
284             Roo.get(this.csvFrame).remove();
285             this.csvFrame= false;
286         }
287         */
288          
289     },
290     
291     buildFromGrid : function()
292     {
293         // get the params from beforeLoad
294         var ds = this.grid.ds;
295         ds.fireEvent('beforeload', ds, {
296             params : this.params
297             
298         });
299         
300          if(ds.sortInfo && ds.remoteSort){
301             var pn = ds.paramNames;
302             this.params[pn["sort"]] = ds.sortInfo.field;
303             this.params[pn["dir"]] = ds.sortInfo.direction;
304         }
305         if (ds.multiSort) {
306             var pn = ds.paramNames;
307             this.params[pn["multisort"]] = Roo.encode( { sort : ds.sortToggle, order: ds.sortOrder });
308         }
309         
310         
311         
312         this.url = this.grid.ds.proxy.conn.url;
313         this.method = this.method || this.grid.ds.proxy.conn.method ;
314         var t = this;
315         // work out the cols
316         
317         if (this.csvCols) {
318             t.params.csvCols = this.csvCols;
319             t.params.csvTitles = this.csvTitles;
320         } else {
321             
322             Roo.each(this.grid.cm.config, function(c,i) {
323                 t.params['csvCols['+i+']'] = c.dataIndex;
324                 t.params['csvTitles['+i+']'] = c.header;
325                 
326             });
327         }
328         if (this.grid.loadMask) {
329             this.grid.loadMask.onLoad();
330         }
331         this.params.limit = this.limit;
332         
333         // do it as a post, as args can get long..
334         
335         this.method = this.method || 'POST';
336         if (this.method  == 'POST') {
337             this.params._get = 1;
338         }
339     }
340      
341 });