PageSourceSearch

https://yeskey.or.kr/resources/js/lib/jquery.fileDownload.js

js yeskey.or.kr collected 2026-10-02 08:34:16 UTC 20,009 bytes, 491 lines download raw bytes

1/*
2* jQuery File Download Plugin v1.4.5
3*
4* http://www.johnculviner.com
5*
6* Copyright (c) 2013 - John Culviner
7*
8* Licensed under the MIT license:
9*   http://www.opensource.org/licenses/mit-license.php
10*
11* !!!!NOTE!!!!
12* You must also write a cookie in conjunction with using this plugin as mentioned in the orignal post:
13* http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/
14* !!!!NOTE!!!!
15*/
16
17(function($, window){
18	// i'll just put them here to get evaluated on script load
19	var htmlSpecialCharsRegEx = /[<>&\r\n"']/gm;
20	var htmlSpecialCharsPlaceHolders = {
21				'<': 'lt;',
22				'>': 'gt;',
23				'&': 'amp;',
24				'\r': "#13;",
25				'\n': "#10;",
26				'"': 'quot;',
27				"'": '#39;' /*single quotes just to be safe, IE8 doesn't support &apos;, so use &#39; instead */
28	};
29
30$.extend({
31    //
32    //$.fileDownload('/path/to/url/', options)
33    //  see directly below for possible 'options'
34    fileDownload: function (fileUrl, options) {
35
36        //provide some reasonable defaults to any unspecified options below
37        var settings = $.extend({
38
39            //
40            //Requires jQuery UI: provide a message to display to the user when the file download is being prepared before the browser's dialog appears
41            //
42            preparingMessageHtml: null,
43
44            //
45            //Requires jQuery UI: provide a message to display to the user when a file download fails
46            //
47            failMessageHtml: null,
48
49            //
50            //the stock android browser straight up doesn't support file downloads initiated by a non GET: http://code.google.com/p/android/issues/detail?id=1780
51            //specify a message here to display if a user tries with an android browser
52            //if jQuery UI is installed this will be a dialog, otherwise it will be an alert
53            //Set to null to disable the message and attempt to download anyway
54            //
55            androidPostUnsupportedMessageHtml: "Unfortunately your Android browser doesn't support this type of file download. Please try again with a different browser.",
56
57            //
58            //Requires jQuery UI: options to pass into jQuery UI Dialog
59            //
60            dialogOptions: { modal: true },
61
62            //
63            //a function to call while the dowload is being prepared before the browser's dialog appears
64            //Args:
65            //  url - the original url attempted
66            //
67            prepareCallback: function (url) { },
68
69            //
70            //a function to call after a file download successfully completed
71            //Args:
72            //  url - the original url attempted
73            //
74            successCallback: function (url) { },
75
76            //
77            //a function to call after a file download request was canceled
78            //Args:
79            //  url - the original url attempted
80            //
81            abortCallback: function (url) { },
82
83            //
84            //a function to call after a file download failed
85            //Args:
86            //  responseHtml    - the html that came back in response to the file download. this won't necessarily come back depending on the browser.
87            //                      in less than IE9 a cross domain error occurs because 500+ errors cause a cross domain issue due to IE subbing out the
88            //                      server's error message with a "helpful" IE built in message
89            //  url             - the original url attempted
90            //  error           - original error cautch from exception
91            //
92            failCallback: function (responseHtml, url, error) { },
93
94            //
95            // the HTTP method to use. Defaults to "GET".
96            //
97            httpMethod: "GET",
98
99            //
100            // if specified will perform a "httpMethod" request to the specified 'fileUrl' using the specified data.
101            // data must be an object (which will be $.param serialized) or already a key=value param string
102            //
103            data: null,
104
105            //
106            //a period in milliseconds to poll to determine if a successful file download has occured or not
107            //
108            checkInterval: 100,
109
110            //
111            //the cookie name to indicate if a file download has occured
112            //
113            cookieName: "fileDownload",
114
115            //
116            //the cookie value for the above name to indicate that a file download has occured
117            //
118            cookieValue: "true",
119
120            //
121            //the cookie path for above name value pair
122            //
123            cookiePath: "/",
124
125            //
126            //if specified it will be used when attempting to clear the above name value pair
127            //useful for when downloads are being served on a subdomain (e.g. downloads.example.com)
128            //
129            cookieDomain: null,
130
131            //
132            //the title for the popup second window as a download is processing in the case of a mobile browser
133            //
134            popupWindowTitle: "Initiating file download...",
135
136            //
137            //Functionality to encode HTML entities for a POST, need this if data is an object with properties whose values contains strings with quotation marks.
138            //HTML entity encoding is done by replacing all &,<,>,',",\r,\n characters.
139            //Note that some browsers will POST the string htmlentity-encoded whilst others will decode it before POSTing.
140            //It is recommended that on the server, htmlentity decoding is done irrespective.
141            //
142            encodeHTMLEntities: true
143
144        }, options);
145
146        var deferred = new $.Deferred();
147
148        //Setup mobile browser detection: Partial credit: http://detectmobilebrowser.com/
149        var userAgent = (navigator.userAgent || navigator.vendor || window.opera).toLowerCase();
150
151        var isIos;                  //has full support of features in iOS 4.0+, uses a new window to accomplish this.
152        var isAndroid;              //has full support of GET features in 4.0+ by using a new window. Non-GET is completely unsupported by the browser. See above for specifying a message.
153        var isOtherMobileBrowser;   //there is no way to reliably guess here so all other mobile devices will GET and POST to the current window.
154
155        if (/ip(ad|hone|od)/.test(userAgent)) {
156
157            isIos = true;
158
159        } else if (userAgent.indexOf('android') !== -1) {
160
161            isAndroid = true;
162
163        } else {
164
165            isOtherMobileBrowser = /avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|playbook|silk|iemobile|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(userAgent) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|
165sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i.test(userAgent.substr(0, 4));
166
167        }
168
169        var httpMethodUpper = settings.httpMethod.toUpperCase();
170
171        if (isAndroid && httpMethodUpper !== "GET" && settings.androidPostUnsupportedMessageHtml) {
172            //the stock android browser straight up doesn't support file downloads initiated by non GET requests: http://code.google.com/p/android/issues/detail?id=1780
173
174            if ($().dialog) {
175                $("<div>").html(settings.androidPostUnsupportedMessageHtml).dialog(settings.dialogOptions);
176            }
177
178            return deferred.reject();
179        }
180
181        var $preparingDialog = null;
182
183        var internalCallbacks = {
184
185            onPrepare: function (url) {
186
187                //wire up a jquery dialog to display the preparing message if specified
188                if (settings.preparingMessageHtml) {
189
190                    $preparingDialog = $("<div>").html(settings.preparingMessageHtml).dialog(settings.dialogOptions);
191
192                } else if (settings.prepareCallback) {
193
194                    settings.prepareCallback(url);
195
196                }
197
198            },
199
200            onSuccess: function (url) {
201
202                //remove the perparing message if it was specified
203                if ($preparingDialog) {
204                    $preparingDialog.dialog('close');
205                }
206
207                settings.successCallback(url);
208
209                deferred.resolve(url);
210            },
211
212            onAbort: function (url) {
213
214                //remove the perparing message if it was specified
215                if ($preparingDialog) {
216                    $preparingDialog.dialog('close');
217                };
218
219                settings.abortCallback(url);
220
221                deferred.reject(url);
222            },
223
224            onFail: function (responseHtml, url, error) {
225
226                //remove the perparing message if it was specified
227                if ($preparingDialog) {
228                    $preparingDialog.dialog('close');
229                }
230
231                //wire up a jquery dialog to display the fail message if specified
232                if (settings.failMessageHtml) {
233                    $("<div>").html(settings.failMessageHtml).dialog(settings.dialogOptions);
234                }
235
236                settings.failCallback(responseHtml, url, error);
237
238                deferred.reject(responseHtml, url);
239            }
240        };
241
242        internalCallbacks.onPrepare(fileUrl);
243
244        //make settings.data a param string if it exists and isn't already
245        if (settings.data !== null && typeof settings.data !== "string") {
246            settings.data = $.param(settings.data);
247        }
248
249
250        var $iframe,
251            downloadWindow,
252            formDoc,
253            $form;
254
255        if (httpMethodUpper === "GET") {
256
257            if (settings.data !== null) {
258                //need to merge any fileUrl params with the data object
259
260                var qsStart = fileUrl.indexOf('?');
261
262                if (qsStart !== -1) {
263                    //we have a querystring in the url
264
265                    if (fileUrl.substring(fileUrl.length - 1) !== "&") {
266                        fileUrl = fileUrl + "&";
267                    }
268                } else {
269
270                    fileUrl = fileUrl + "?";
271                }
272
273                fileUrl = fileUrl + settings.data;
274            }
275
276            if (isIos || isAndroid) {
277
278                downloadWindow = window.open(fileUrl);
279                downloadWindow.document.title = settings.popupWindowTitle;
280                window.focus();
281
282            } else if (isOtherMobileBrowser) {
283
284                window.location(fileUrl);
285
286            } else {
287
288                //create a temporary iframe that is used to request the fileUrl as a GET request
289                $iframe = $("<iframe>")
290                    .hide()
291                    .prop("src", fileUrl)
292                    .appendTo("body");
293            }
294
295        } else {
296
297            var formInnerHtml = "";
298
299            if (settings.data !== null) {
300
301                $.each(settings.data.replace(/\+/g, ' ').split("&"), function () {
302
303                    var kvp = this.split("=");
304
305                    //Issue: When value contains sign '=' then the kvp array does have more than 2 items. We have to join value back
306                    var k = kvp[0];
307                    kvp.shift();
308                    var v = kvp.join("=");
309                    kvp = [k, v];
310
311                    var key = settings.encodeHTMLEntities ? htmlSpecialCharsEntityEncode(decodeURIComponent(kvp[0])) : decodeURIComponent(kvp[0]);
312                    if (key) {
313                        var value = settings.encodeHTMLEntities ? htmlSpecialCharsEntityEncode(decodeURIComponent(kvp[1])) : decodeURIComponent(kvp[1]);
314                    formInnerHtml += '<input type="hidden" name="' + key + '" value="' + value + '" />';
315                    }
316                });
317            }
318
319            if (isOtherMobileBrowser) {
320
321                $form = $("<form>").appendTo("body");
322                $form.hide()
323                    .prop('method', settings.httpMethod)
324                    .prop('action', fileUrl)
325                    .html(formInnerHtml);
326
327            } else {
328
329                if (isIos) {
330
331                    downloadWindow = window.open("about:blank");
332                    downloadWindow.document.title = settings.popupWindowTitle;
333                    formDoc = downloadWindow.document;
334                    window.focus();
335
336                } else {
337
338                    $iframe = $("<iframe style='display: none' src='about:blank'></iframe>").appendTo("body");
339                    formDoc = getiframeDocument($iframe);
340                }
341
342                formDoc.write("<html><head></head><body><form method='" + settings.httpMethod + "' action='" + fileUrl + "'>" + formInnerHtml + "</form>" + settings.popupWindowTitle + "</body></html>");
343                $form = $(formDoc).find('form');
344            }
345
346            $form.submit();
347        }
348
349
350        //check if the file download has completed every checkInterval ms
351        setTimeout(checkFileDownloadComplete, settings.checkInterval);
352
353
354        function checkFileDownloadComplete() {
355            //has the cookie been written due to a file download occuring?
356
357            var cookieValue = settings.cookieValue;
358            if(typeof cookieValue == 'string') {
359                cookieValue = cookieValue.toLowerCase();
360            }
361
362            var lowerCaseCookie = settings.cookieName.toLowerCase() + "=" + cookieValue;
363
364            if (document.cookie.toLowerCase().indexOf(lowerCaseCookie) > -1) {
365
366                //execute specified callback
367                internalCallbacks.onSuccess(fileUrl);
368
369                //remove cookie
370                var cookieData = settings.cookieName + "=; path=" + settings.cookiePath + "; expires=" + new Date(0).toUTCString() + ";";
371                if (settings.cookieDomain) cookieData += " domain=" + settings.cookieDomain + ";";
372                document.cookie = cookieData;
373
374                //remove iframe
375                cleanUp(false);
376
377                return;
378            }
379
380            //has an error occured?
381            //if neither containers exist below then the file download is occuring on the current window
382            if (downloadWindow || $iframe) {
383
384                //has an error occured?
385                try {
386
387                    var formDoc = downloadWindow ? downloadWindow.document : getiframeDocument($iframe);
388
389                    if (formDoc && formDoc.body !== null && formDoc.body.innerHTML.length) {
390
391                        var isFailure = true;
392
393                        if ($form && $form.length) {
394                            var $contents = $(formDoc.body).contents().first();
395
396                            try {
397                                if ($contents.length && $contents[0] === $form[0]) {
398                                    isFailure = false;
399                                }
400                            } catch (e) {
401                                if (e && e.number == -2146828218) {
402                                    // IE 8-10 throw a permission denied after the form reloads on the "$contents[0] === $form[0]" comparison
403                                    isFailure = true;
404                                } else {
405                                    throw e;
406                                }
407                            }
408                        }
409
410                        if (isFailure) {
411                            // IE 8-10 don't always have the full content available right away, they need a litle bit to finish
412                            setTimeout(function () {
413                                internalCallbacks.onFail(formDoc.body.innerHTML, fileUrl);
414                                cleanUp(true);
415                            }, 100);
416
417                            return;
418                        }
419                    }
420                }
421                catch (err) {
422
423                    //500 error less than IE9
424                    internalCallbacks.onFail('', fileUrl, err);
425
426                    cleanUp(true);
427
428                    return;
429                }
430            }
431
432
433            //keep checking...
434            setTimeout(checkFileDownloadComplete, settings.checkInterval);
435        }
436
437        //gets an iframes document in a cross browser compatible manner
438        function getiframeDocument($iframe) {
439            var iframeDoc = $iframe[0].contentWindow || $iframe[0].contentDocument;
440            if (iframeDoc.document) {
441                iframeDoc = iframeDoc.document;
442            }
443            return iframeDoc;
444        }
445
446        function cleanUp(isFailure) {
447
448            setTimeout(function() {
449
450                if (downloadWindow) {
451
452                    if (isAndroid) {
453                        downloadWindow.close();
454                    }
455
456                    if (isIos) {
457                        if (downloadWindow.focus) {
458                            downloadWindow.focus(); //ios safari bug doesn't allow a window to be closed unless it is focused
459                            if (isFailure) {
460                                downloadWindow.close();
461                            }
462                        }
463                    }
464                }
465
466                //iframe cleanup appears to randomly cause the download to fail
467                //not doing it seems better than failure...
468                //if ($iframe) {
469                //    $iframe.remove();
470                //}
471
472            }, 0);
473        }
474
475
476        function htmlSpecialCharsEntityEncode(str) {
477            return str.replace(htmlSpecialCharsRegEx, function(match) {
478                return '&' + htmlSpecialCharsPlaceHolders[match];
479        	});
480        }
481        var promise = deferred.promise();
482        promise.abort = function() {
483            cleanUp();
484            $iframe.attr('src', '').html('');
485            internalCallbacks.onAbort(fileUrl);
486        };
487        return promise;
488    }
489});
490
491})(jQuery, this || window);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.