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     this.params = {};
42     
43     Roo.apply(this, cfg);
44      
45     if (this.grid) {
46         
47         this.buildFromGrid();
48         Roo.log(this);
49     }
50     
51     
52     if (this.newWindow && this.method == 'GET') {
53         // as ie seems buggy...
54         window.open( this.url + '?' + Roo.urlEncode(this.params || {}), '_blank');
55         return ; 
56         
57     }
58    
59     
60     
61     //this.submit = false;
62     //this.createCsvFrame();
63     
64     //var requested = 0;
65      
66     //Roo.EventManager.on( this.csvFrame, 'load', this.onLoad, this);
67     
68     
69     //--- simple method..
70     this.method = this.method || 'GET';
71     
72     if (this.method == 'GET' && !this.params) {
73         (function() {
74             
75             
76             this.createCsvFrame();
77             //Roo.EventManager.on( this.csvFrame, 'load', this.onLoad, this);
78             this.submit = true;
79             this.csvFrame.src = cfg.url;
80             //this.cleanup.defer(cfg.timeout || 30000,this);
81         }).defer(100, this);
82         
83        
84         return;
85     }
86     
87     
88     Roo.log("creating form?");
89     
90     this.form = new FormData();
91     /*
92     var b = Roo.get(document.body);
93     this.form = b.createChild({
94         tag: 'form',
95         method : this.method,
96         action : this.url,
97         target : this.newWindow ? '_new' : this.csvFrame.id,
98         enctype : 'multipart/form-data'
99     });
100     **/
101 //    
102 //    if(this.doctype == 'pdf'){
103 //        this.pdfEmbed = b.createChild({
104 //            tag: 'embed',
105 //            src : this.url,
106 //            pluginspage : 'http://www.adobe.com/products/acrobat/readstep2.html',
107 //            alt: this.doctype
108 //        });
109 //    }
110  
111     Roo.log(this.params);
112     for(var i in this.params) {
113         this.form.append(i, this.params[i]);
114         /*
115         var el = this.form.createChild( {
116             ns : 'html',
117             tag : 'input',
118             
119             type: 'hidden',
120             name : i,
121             value : this.params[i]
122         });
123         */
124         
125         
126     }
127     var req = new XMLHttpRequest();
128     req.open(this.method, this.url);
129     
130     var _t = this;
131     req.onload = function( ev )
132     {
133         if (req.status == 200) {
134             _t.success ? _t.success(ev) : '';
135         } else {
136             _t.failure ? _t.failure(ev) : '';
137         }
138         
139     }
140     
141     req.send(this.form);
142     /*
143     (function() {
144         this.submit = true;
145         this.form.dom.submit();
146         this.cleanup.defer(this.timeout || 30000,this);
147     }).defer(100, this);
148     */
149      
150  
151 }
152
153 Roo.apply(Pman.Download.prototype, {
154     
155     /**
156      * @type {HTMLIframe} the iframe to download into.
157      */
158      
159     csvFrame : false,
160     
161     // private
162     form : false,
163     
164     limit : 9999,
165     
166     newWindow : false,
167     
168     method : 'GET',
169     
170     success : false,
171     failure : false,
172     
173     // private..
174     //used by simple GET method.
175     createCsvFrame: function()
176     {
177         if (this.csvFrame) {
178             document.body.removeChild(this.csvFrame);
179         }
180             
181         var id = Roo.id();
182         this.csvFrame = document.createElement('iframe');
183         this.csvFrame.id = id;
184         this.csvFrame.name = id;
185         this.csvFrame.className = 'x-hidden';
186         //if(Roo.isIE){
187             this.csvFrame.src = Roo.SSL_SECURE_URL;
188         //}
189         document.body.appendChild(this.csvFrame);
190
191         if(Roo.isIE){
192             document.frames[id].name = id;
193         }
194         
195     },
196     /* not used as it didn't work..
197     onLoad : function()
198     {
199        // requested++; // second request is real one..
200        // if (requested < 2) {
201        //     return;
202         //} // n
203         Roo.log('onload?');
204         if (!this.submit) {
205             return false;
206         }
207         //return false;
208       
209         var frame = this.csvFrame;
210         var success  = true; 
211         try { 
212             var doc = Roo.isIE ? 
213                 frame.contentWindow.document : 
214                 (frame.contentDocument || window.frames[Pman.Download.csvFrame.id].document);
215             
216             
217             if(doc && doc.body && doc.body.innerHTML.length){
218               //  alert(doc.body.innerHTML);
219                   
220                 Roo.MessageBox.alert("Download Error", doc.body.innerHTML);
221                 success  = false;
222                 if (this.failure) {
223                     this.failure();
224                 }
225                 return true;
226             }
227             
228             Roo.log(doc.body.innerHTML);
229              
230         }
231         catch(e) {
232             Roo.log(e.toString());
233             Roo.log(e);
234         }
235         if (this.success) {
236             this.success();
237         }
238         // we can not actually do anything with the frame... as it may actually still be downloading..
239         return true;
240     
241         this.cleanup();
242         
243         // this will never fire.. see 
244         // 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
245         if (this.success && success) {
246             
247             this.success();
248         }
249         return false;
250         
251
252     },
253      */
254     // private - clean up download elements.
255     cleanup :function()
256     {
257        /* Roo.log('cleanup?');
258         if (this.form) {
259             this.form.remove();
260             this.form= false;
261         
262         }
263         
264         if (this.csvFrame) {
265             Roo.EventManager.removeListener(this.csvFrame, 'load', this.onLoad, this);
266             Roo.get(this.csvFrame).remove();
267             this.csvFrame= false;
268         }
269         */
270          
271     },
272     
273     buildFromGrid : function()
274     {
275         // get the params from beforeLoad
276         var ds = this.grid.ds;
277         ds.fireEvent('beforeload', ds, {
278             params : this.params
279             
280         });
281         
282          if(ds.sortInfo && ds.remoteSort){
283             var pn = ds.paramNames;
284             this.params[pn["sort"]] = ds.sortInfo.field;
285             this.params[pn["dir"]] = ds.sortInfo.direction;
286         }
287         if (ds.multiSort) {
288             var pn = ds.paramNames;
289             this.params[pn["multisort"]] = Roo.encode( { sort : ds.sortToggle, order: ds.sortOrder });
290         }
291         
292         
293         
294         this.url = this.grid.ds.proxy.conn.url;
295         this.method = this.method || this.grid.ds.proxy.conn.method ;
296         var t = this;
297         // work out the cols
298         
299         if (this.csvCols) {
300             t.params.csvCols = this.csvCols;
301             t.params.csvTitles = this.csvTitles;
302         } else {
303             
304             Roo.each(this.grid.cm.config, function(c,i) {
305                 t.params['csvCols['+i+']'] = c.dataIndex;
306                 t.params['csvTitles['+i+']'] = c.header;
307                 
308             });
309         }
310         if (this.grid.loadMask) {
311             this.grid.loadMask.onLoad();
312         }
313         this.params.limit = this.limit;
314         
315         // do it as a post, as args can get long..
316         
317         this.method = this.method || 'POST';
318         if (this.method  == 'POST') {
319             this.params._get = 1;
320         }
321     }
322      
323 });