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         var url = cfg.url || this.url;
55         var params = cfg.params || this.params;
56         
57         window.open( this.url + '?' + Roo.urlEncode(this.params || {}), '_blank');
58         return ; 
59         
60     }
61    
62     
63     
64     this.submit = false;
65     this.createCsvFrame();
66     
67     var requested = 0;
68      
69     Roo.EventManager.on( this.csvFrame, 'load', this.onLoad, this);
70     
71     
72     //--- simple method..
73     this.method = this.method || 'GET';
74     
75     if (this.method == 'GET' && !this.params) {
76         (function() {
77             this.submit = true;
78             this.csvFrame.src = cfg.url;
79             //this.cleanup.defer(cfg.timeout || 30000,this);
80         }).defer(100, this);
81         
82        
83         return;
84     }
85     
86     
87     Roo.log("creating form?");
88     
89     var b = Roo.get(document.body);
90     this.form = b.createChild({
91         tag: 'form',
92         method : this.method,
93         action : this.url,
94         target : this.newWindow ? '_new' : this.csvFrame.id,
95         enctype : 'multipart/form-data'
96     });
97 //    
98 //    if(this.doctype == 'pdf'){
99 //        this.pdfEmbed = b.createChild({
100 //            tag: 'embed',
101 //            src : this.url,
102 //            pluginspage : 'http://www.adobe.com/products/acrobat/readstep2.html',
103 //            alt: this.doctype
104 //        });
105 //    }
106  
107  
108     for(var i in this.params) {
109         
110         var el = this.form.createChild( {
111             ns : 'html',
112             tag : 'input',
113             
114             type: 'hidden',
115             name : i,
116             value : this.params[i]
117         });
118         
119         
120     }
121     
122     (function() {
123         this.submit = true;
124         this.form.dom.submit();
125         this.cleanup.defer(this.timeout || 30000,this);
126     }).defer(100, this);
127     
128      
129  
130 }
131
132 Roo.apply(Pman.Download.prototype, {
133     
134     /**
135      * @type {HTMLIframe} the iframe to download into.
136      */
137      
138     csvFrame : false,
139     
140     // private
141     form : false,
142     
143     limit : 9999,
144     
145     newWindow : false,
146     
147     method : 'GET',
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                  
198                 
199             }
200             
201             Roo.log(doc.body.innerHTML);
202              
203         }
204         catch(e) {
205             Roo.log(e.toString());
206             Roo.log(e);
207         }
208         // we can not actually do anything with the frame... as it may actually still be downloading..
209         return true;
210     
211         this.cleanup();
212         
213         // this will never fire.. see 
214         // 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
215         if (this.success && success) {
216             
217             this.success();
218         }
219         return false;
220         
221
222     },
223     
224     // private - clean up download elements.
225     cleanup :function()
226     {
227         Roo.log('cleanup?');
228         if (this.form) {
229             this.form.remove();
230             this.form= false;
231         
232         }
233         
234         if (this.csvFrame) {
235             Roo.EventManager.removeListener(this.csvFrame, 'load', this.onLoad, this);
236             Roo.get(this.csvFrame).remove();
237             this.csvFrame= false;
238         }
239          
240     },
241     
242     buildFromGrid : function()
243     {
244         // get the params from beforeLoad
245         var ds = this.grid.ds;
246         ds.fireEvent('beforeload', ds, {
247             params : this.params
248             
249         });
250         
251          if(ds.sortInfo && ds.remoteSort){
252             var pn = ds.paramNames;
253             this.params[pn["sort"]] = ds.sortInfo.field;
254             this.params[pn["dir"]] = ds.sortInfo.direction;
255         }
256         if (ds.multiSort) {
257             var pn = ds.paramNames;
258             this.params[pn["multisort"]] = Roo.encode( { sort : ds.sortToggle, order: ds.sortOrder });
259         }
260         
261         
262         
263         this.url = this.grid.ds.proxy.conn.url;
264         this.method = this.method || this.grid.ds.proxy.conn.method ;
265         var t = this;
266         // work out the cols
267         
268         if (this.csvCols) {
269             t.params.csvCols = this.csvCols;
270             t.params.csvTitles = this.csvTitles;
271         } else {
272             
273             Roo.each(this.grid.cm.config, function(c,i) {
274                 t.params['csvCols['+i+']'] = c.dataIndex;
275                 t.params['csvTitles['+i+']'] = c.header;
276                 
277             });
278         }
279         if (this.grid.loadMask) {
280             this.grid.loadMask.onLoad();
281         }
282         this.params.limit = this.limit;
283         
284         // do it as a post, as args can get long..
285         
286         this.method = this.method || 'POST';
287         if (this.method  == 'POST') {
288             this.params._get = 1;
289         }
290     }
291      
292 });