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