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