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