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