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