fix #8131 - chinese translations
[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 {Object}  params  params to send
22 * @cfg {String} url     Location to download from.
23 * @cfg {String} method (GET|POST)    GET or POST (default GET), POST will create a form, and post that into the hidden frame.
24 * @cfg {Boolean} newWindow (optional) download to new window
25 * @cfg {String} doctype (optional) download PDF to new window
26 * @cfg {Boolean} limit (optional) limit for grid downloads.
27 * @cfg {Boolean} showDownloading default false - show a dialog indicating that the file is downloading
28  * @cfg {String} csvCols  - use '*' to override grid coluns
29  * @cfg {String} csvTitles - use '*' to override grid coluns
30  * @cfg {String} hiddenCols - default 'show'  (use 'hide' to not display them on download)
31  
32  
33 * @cfg {Function} success (optional) MAY fire on download completed (fails on attachments)..
34 * @cfg {Number} timeout (optional) in milliseconds before it gives up (default 30000 = 30s)
35 * @cfg {Roo.grid.Grid} grid (optional) if you want to just download a grid, (without renderers..)
36
37 */
38
39 Pman.Download = function(cfg)
40 {
41     
42    
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     this.params._get = 1; // always do a post request, with _get passed
116     for(var i in this.params) {
117         this.form.append(i, this.params[i]);
118         /*
119         var el = this.form.createChild( {
120             ns : 'html',
121             tag : 'input',
122             
123             type: 'hidden',
124             name : i,
125             value : this.params[i]
126         });
127         */
128         
129         
130     }
131     var req = new XMLHttpRequest();
132     req.responseType = 'blob';
133     
134     req.open('POST', this.url);
135     
136     var _t = this;
137     req.onload = function( ev )
138     {
139         if (req.status == 200) {
140             Roo.log(ev);
141             var cd = req.getResponseHeader('Content-Disposition');
142             
143             var filename = '';
144             var matches = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/.exec(cd);
145             if (matches != null && matches[1]) { 
146                 filename = matches[1].replace(/['"]/g, '');
147             }
148             
149             var blob = new Blob([req.response], {type: req.responseType });
150             
151             var a = document.createElement("a");
152             a.style = "display: none";
153             document.body.appendChild(a);
154             var url = window.URL.createObjectURL(blob);
155             a.href = url;
156             a.download = filename;
157              a.click();
158             //release the reference to the file by revoking the Object URL
159             window.URL.revokeObjectURL(url);
160             
161             _t.success ? _t.success(ev) : '';
162         } else {
163             _t.failure ? _t.failure(ev) : '';
164         }
165         
166     }
167     if (this.showDownloading) {
168         Roo.MessageBox.alert("Downloading", "The file should download shortly");
169     }
170     req.send(this.form);
171     /*
172     (function() {
173         this.submit = true;
174         this.form.dom.submit();
175         this.cleanup.defer(this.timeout || 30000,this);
176     }).defer(100, this);
177     */
178      
179  
180 }
181
182 Roo.apply(Pman.Download.prototype, {
183     
184     /**
185      * @type {HTMLIframe} the iframe to download into.
186      */
187      
188     csvFrame : false,
189     
190     // private
191     form : false,
192     
193     limit : 9999,
194     
195     newWindow : false,
196     
197     method : 'GET',
198     
199     success : false,
200     failure : false,
201     
202     hiddenCols : 'show', // set to 'hide' to hide them..
203     
204     showDownloading : false,
205     // private..
206     //used by simple GET method.
207     createCsvFrame: function()
208     {
209         if (this.csvFrame) {
210             document.body.removeChild(this.csvFrame);
211         }
212             
213         var id = Roo.id();
214         this.csvFrame = document.createElement('iframe');
215         this.csvFrame.id = id;
216         this.csvFrame.name = id;
217         this.csvFrame.className = 'x-hidden';
218         //if(Roo.isIE){
219             this.csvFrame.src = Roo.SSL_SECURE_URL;
220         //}
221         document.body.appendChild(this.csvFrame);
222
223         if(Roo.isIE){
224             document.frames[id].name = id;
225         }
226         
227     },
228     /* not used as it didn't work..
229     onLoad : function()
230     {
231        // requested++; // second request is real one..
232        // if (requested < 2) {
233        //     return;
234         //} // n
235         Roo.log('onload?');
236         if (!this.submit) {
237             return false;
238         }
239         //return false;
240       
241         var frame = this.csvFrame;
242         var success  = true; 
243         try { 
244             var doc = Roo.isIE ? 
245                 frame.contentWindow.document : 
246                 (frame.contentDocument || window.frames[Pman.Download.csvFrame.id].document);
247             
248             
249             if(doc && doc.body && doc.body.innerHTML.length){
250               //  alert(doc.body.innerHTML);
251                   
252                 Roo.MessageBox.alert("Download Error", doc.body.innerHTML);
253                 success  = false;
254                 if (this.failure) {
255                     this.failure();
256                 }
257                 return true;
258             }
259             
260             Roo.log(doc.body.innerHTML);
261              
262         }
263         catch(e) {
264             Roo.log(e.toString());
265             Roo.log(e);
266         }
267         if (this.success) {
268             this.success();
269         }
270         // we can not actually do anything with the frame... as it may actually still be downloading..
271         return true;
272     
273         this.cleanup();
274         
275         // this will never fire.. see 
276         // 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
277         if (this.success && success) {
278             
279             this.success();
280         }
281         return false;
282         
283
284     },
285      */
286     // private - clean up download elements.
287     cleanup :function()
288     {
289        /* Roo.log('cleanup?');
290         if (this.form) {
291             this.form.remove();
292             this.form= false;
293         
294         }
295         
296         if (this.csvFrame) {
297             Roo.EventManager.removeListener(this.csvFrame, 'load', this.onLoad, this);
298             Roo.get(this.csvFrame).remove();
299             this.csvFrame= false;
300         }
301         */
302          
303     },
304     
305     buildFromGrid : function()
306     {
307         // get the params from beforeLoad
308         var ds = this.grid.ds;
309         ds.fireEvent('beforeload', ds, {
310             params : this.params
311             
312         });
313         
314         if(ds.sortInfo && ds.remoteSort){
315             var pn = ds.paramNames;
316             this.params[pn["sort"]] = ds.sortInfo.field;
317             this.params[pn["dir"]] = ds.sortInfo.direction;
318         }
319         if (ds.multiSort) {
320             var pn = ds.paramNames;
321             this.params[pn["multisort"]] = Roo.encode( { sort : ds.sortToggle, order: ds.sortOrder });
322         }
323         
324         
325         
326         this.url = this.grid.ds.proxy.conn.url;
327         this.method = this.method || this.grid.ds.proxy.conn.method ;
328         var t = this;
329         // work out the cols
330         
331         if (this.csvCols) {
332             t.params.csvCols = this.csvCols;
333             t.params.csvTitles = this.csvTitles;
334         } else {
335             
336             Roo.each(this.grid.cm.config, function(c,i) {
337                 
338                 if (t.hiddenCols != 'show' && t.grid.cm.isHidden(i)) {
339                     return;
340                 }
341                 
342                 t.params['csvCols['+i+']'] = c.dataIndex;
343                 t.params['csvTitles['+i+']'] = c.header;
344                 
345             });
346         }
347         if (this.grid.loadMask) {
348             this.grid.loadMask.onLoad();
349         }
350         this.params.limit = this.limit;
351         
352         // do it as a post, as args can get long..
353         
354         this.method =   'POST';
355         if (this.method  == 'POST') {
356             this.params._get = 1;
357         }
358     }
359      
360 });