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     createCsvFrame: function()
171     {
172         if (this.csvFrame) {
173             document.body.removeChild(this.csvFrame);
174         }
175             
176         var id = Roo.id();
177         this.csvFrame = document.createElement('iframe');
178         this.csvFrame.id = id;
179         this.csvFrame.name = id;
180         this.csvFrame.className = 'x-hidden';
181         //if(Roo.isIE){
182             this.csvFrame.src = Roo.SSL_SECURE_URL;
183         //}
184         document.body.appendChild(this.csvFrame);
185
186         if(Roo.isIE){
187             document.frames[id].name = id;
188         }
189         
190     },
191     
192     onLoad : function()
193     {
194        // requested++; // second request is real one..
195        // if (requested < 2) {
196        //     return;
197         //} // n
198         Roo.log('onload?');
199         if (!this.submit) {
200             return false;
201         }
202         //return false;
203       
204         var frame = this.csvFrame;
205         var success  = true; 
206         try { 
207             var doc = Roo.isIE ? 
208                 frame.contentWindow.document : 
209                 (frame.contentDocument || window.frames[Pman.Download.csvFrame.id].document);
210             
211             
212             if(doc && doc.body && doc.body.innerHTML.length){
213               //  alert(doc.body.innerHTML);
214                   
215                 Roo.MessageBox.alert("Download Error", doc.body.innerHTML);
216                 success  = false;
217                 if (this.failure) {
218                     this.failure();
219                 }
220                 return true;
221             }
222             
223             Roo.log(doc.body.innerHTML);
224              
225         }
226         catch(e) {
227             Roo.log(e.toString());
228             Roo.log(e);
229         }
230         if (this.success) {
231             this.success();
232         }
233         // we can not actually do anything with the frame... as it may actually still be downloading..
234         return true;
235     
236         this.cleanup();
237         
238         // this will never fire.. see 
239         // 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
240         if (this.success && success) {
241             
242             this.success();
243         }
244         return false;
245         
246
247     },
248     
249     // private - clean up download elements.
250     cleanup :function()
251     {
252        /* Roo.log('cleanup?');
253         if (this.form) {
254             this.form.remove();
255             this.form= false;
256         
257         }
258         
259         if (this.csvFrame) {
260             Roo.EventManager.removeListener(this.csvFrame, 'load', this.onLoad, this);
261             Roo.get(this.csvFrame).remove();
262             this.csvFrame= false;
263         }
264         */
265          
266     },
267     
268     buildFromGrid : function()
269     {
270         // get the params from beforeLoad
271         var ds = this.grid.ds;
272         ds.fireEvent('beforeload', ds, {
273             params : this.params
274             
275         });
276         
277          if(ds.sortInfo && ds.remoteSort){
278             var pn = ds.paramNames;
279             this.params[pn["sort"]] = ds.sortInfo.field;
280             this.params[pn["dir"]] = ds.sortInfo.direction;
281         }
282         if (ds.multiSort) {
283             var pn = ds.paramNames;
284             this.params[pn["multisort"]] = Roo.encode( { sort : ds.sortToggle, order: ds.sortOrder });
285         }
286         
287         
288         
289         this.url = this.grid.ds.proxy.conn.url;
290         this.method = this.method || this.grid.ds.proxy.conn.method ;
291         var t = this;
292         // work out the cols
293         
294         if (this.csvCols) {
295             t.params.csvCols = this.csvCols;
296             t.params.csvTitles = this.csvTitles;
297         } else {
298             
299             Roo.each(this.grid.cm.config, function(c,i) {
300                 t.params['csvCols['+i+']'] = c.dataIndex;
301                 t.params['csvTitles['+i+']'] = c.header;
302                 
303             });
304         }
305         if (this.grid.loadMask) {
306             this.grid.loadMask.onLoad();
307         }
308         this.params.limit = this.limit;
309         
310         // do it as a post, as args can get long..
311         
312         this.method = this.method || 'POST';
313         if (this.method  == 'POST') {
314             this.params._get = 1;
315         }
316     }
317      
318 });