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