Pman.Download.js
[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 blob = new Blob([this.response], {type: req.responseType });
139             
140             var a = document.createElement("a");
141             a.style = "display: none";
142             document.body.appendChild(a);
143             var url = window.URL.createObjectURL(blob);
144             a.href = url;
145             a.download = 'myFile.pdf';
146              a.click();
147             //release the reference to the file by revoking the Object URL
148             window.URL.revokeObjectURL(url);
149             
150             _t.success ? _t.success(ev) : '';
151         } else {
152             _t.failure ? _t.failure(ev) : '';
153         }
154         
155     }
156     
157     req.send(this.form);
158     /*
159     (function() {
160         this.submit = true;
161         this.form.dom.submit();
162         this.cleanup.defer(this.timeout || 30000,this);
163     }).defer(100, this);
164     */
165      
166  
167 }
168
169 Roo.apply(Pman.Download.prototype, {
170     
171     /**
172      * @type {HTMLIframe} the iframe to download into.
173      */
174      
175     csvFrame : false,
176     
177     // private
178     form : false,
179     
180     limit : 9999,
181     
182     newWindow : false,
183     
184     method : 'GET',
185     
186     success : false,
187     failure : false,
188     
189     // private..
190     //used by simple GET method.
191     createCsvFrame: function()
192     {
193         if (this.csvFrame) {
194             document.body.removeChild(this.csvFrame);
195         }
196             
197         var id = Roo.id();
198         this.csvFrame = document.createElement('iframe');
199         this.csvFrame.id = id;
200         this.csvFrame.name = id;
201         this.csvFrame.className = 'x-hidden';
202         //if(Roo.isIE){
203             this.csvFrame.src = Roo.SSL_SECURE_URL;
204         //}
205         document.body.appendChild(this.csvFrame);
206
207         if(Roo.isIE){
208             document.frames[id].name = id;
209         }
210         
211     },
212     /* not used as it didn't work..
213     onLoad : function()
214     {
215        // requested++; // second request is real one..
216        // if (requested < 2) {
217        //     return;
218         //} // n
219         Roo.log('onload?');
220         if (!this.submit) {
221             return false;
222         }
223         //return false;
224       
225         var frame = this.csvFrame;
226         var success  = true; 
227         try { 
228             var doc = Roo.isIE ? 
229                 frame.contentWindow.document : 
230                 (frame.contentDocument || window.frames[Pman.Download.csvFrame.id].document);
231             
232             
233             if(doc && doc.body && doc.body.innerHTML.length){
234               //  alert(doc.body.innerHTML);
235                   
236                 Roo.MessageBox.alert("Download Error", doc.body.innerHTML);
237                 success  = false;
238                 if (this.failure) {
239                     this.failure();
240                 }
241                 return true;
242             }
243             
244             Roo.log(doc.body.innerHTML);
245              
246         }
247         catch(e) {
248             Roo.log(e.toString());
249             Roo.log(e);
250         }
251         if (this.success) {
252             this.success();
253         }
254         // we can not actually do anything with the frame... as it may actually still be downloading..
255         return true;
256     
257         this.cleanup();
258         
259         // this will never fire.. see 
260         // 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
261         if (this.success && success) {
262             
263             this.success();
264         }
265         return false;
266         
267
268     },
269      */
270     // private - clean up download elements.
271     cleanup :function()
272     {
273        /* Roo.log('cleanup?');
274         if (this.form) {
275             this.form.remove();
276             this.form= false;
277         
278         }
279         
280         if (this.csvFrame) {
281             Roo.EventManager.removeListener(this.csvFrame, 'load', this.onLoad, this);
282             Roo.get(this.csvFrame).remove();
283             this.csvFrame= false;
284         }
285         */
286          
287     },
288     
289     buildFromGrid : function()
290     {
291         // get the params from beforeLoad
292         var ds = this.grid.ds;
293         ds.fireEvent('beforeload', ds, {
294             params : this.params
295             
296         });
297         
298          if(ds.sortInfo && ds.remoteSort){
299             var pn = ds.paramNames;
300             this.params[pn["sort"]] = ds.sortInfo.field;
301             this.params[pn["dir"]] = ds.sortInfo.direction;
302         }
303         if (ds.multiSort) {
304             var pn = ds.paramNames;
305             this.params[pn["multisort"]] = Roo.encode( { sort : ds.sortToggle, order: ds.sortOrder });
306         }
307         
308         
309         
310         this.url = this.grid.ds.proxy.conn.url;
311         this.method = this.method || this.grid.ds.proxy.conn.method ;
312         var t = this;
313         // work out the cols
314         
315         if (this.csvCols) {
316             t.params.csvCols = this.csvCols;
317             t.params.csvTitles = this.csvTitles;
318         } else {
319             
320             Roo.each(this.grid.cm.config, function(c,i) {
321                 t.params['csvCols['+i+']'] = c.dataIndex;
322                 t.params['csvTitles['+i+']'] = c.header;
323                 
324             });
325         }
326         if (this.grid.loadMask) {
327             this.grid.loadMask.onLoad();
328         }
329         this.params.limit = this.limit;
330         
331         // do it as a post, as args can get long..
332         
333         this.method = this.method || 'POST';
334         if (this.method  == 'POST') {
335             this.params._get = 1;
336         }
337     }
338      
339 });