1/* 2* jQuery File Download Plugin v1.4.4 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 ', so use ' 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 dialog/ribbon has appeared 71 //Args: 72 // url - the original url attempted 73 // 74 successCallback: function (url) { }, 75 76 // 77 //a function to call after a file download dialog/ribbon has appeared 78 //Args: 79 // responseHtml - the html that came back in response to the file download. this won't necessarily come back depending on the browser. 80 // in less than IE9 a cross domain error occurs because 500+ errors cause a cross domain issue due to IE subbing out the 81 // server's error message with a "helpful" IE built in message 82 // url - the original url attempted 83 // error - original error cautch from exception 84 // 85 failCallback: function (responseHtml, url, error) { }, 86 87 // 88 // the HTTP method to use. Defaults to "GET". 89 // 90 httpMethod: "GET", 91 92 // 93 // if specified will perform a "httpMethod" request to the specified 'fileUrl' using the specified data. 94 // data must be an object (which will be $.param serialized) or already a key=value param string 95 // 96 data: null, 97 98 // 99 //a period in milliseconds to poll to determine if a successful file download has occured or not 100 // 101 checkInterval: 100, 102 103 // 104 //the cookie name to indicate if a file download has occured 105 // 106 cookieName: "fileDownload", 107 108 // 109 //the cookie value for the above name to indicate that a file download has occured 110 // 111 cookieValue: "true", 112 113 // 114 //the cookie path for above name value pair 115 // 116 cookiePath: "/", 117 118 // 119 //if specified it will be used when attempting to clear the above name value pair 120 //useful for when downloads are being served on a subdomain (e.g. downloads.example.com) 121 // 122 cookieDomain: null, 123 124 // 125 //the title for the popup second window as a download is processing in the case of a mobile browser 126 // 127 popupWindowTitle: "Initiating file download...", 128 129 // 130 //Functionality to encode HTML entities for a POST, need this if data is an object with properties whose values contains strings with quotation marks. 131 //HTML entity encoding is done by replacing all &,<,>,',",\r,\n characters. 132 //Note that some browsers will POST the string htmlentity-encoded whilst others will decode it before POSTing. 133 //It is recommended that on the server, htmlentity decoding is done irrespective. 134 // 135 encodeHTMLEntities: true 136 137 }, options); 138 139 var deferred = new $.Deferred(); 140 141 //Setup mobile browser detection: Partial credit: http://detectmobilebrowser.com/ 142 var userAgent = (navigator.userAgent || navigator.vendor || window.opera).toLowerCase(); 143 144 var isIos; //has full support of features in iOS 4.0+, uses a new window to accomplish this. 145 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. 146 var isOtherMobileBrowser; //there is no way to reliably guess here so all other mobile devices will GET and POST to the current window. 147 148 if (/ip(ad|hone|od)/.test(userAgent)) { 149 150 isIos = true; 151 152 } else if (userAgent.indexOf('android') !== -1) { 153 154 isAndroid = true; 155 156 } else { 157 158 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 )|sy(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)); 159 160 } 161 162 var httpMethodUpper = settings.httpMethod.toUpperCase(); 163 164 if (isAndroid && httpMethodUpper !== "GET" && settings.androidPostUnsupportedMessageHtml) { 165 //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 166 167 if ($().dialog) { 168 $("<div>").html(settings.androidPostUnsupportedMessageHtml).dialog(settings.dialogOptions); 169 } else { 170 alert(settings.androidPostUnsupportedMessageHtml); 171 } 172 173 return deferred.reject(); 174 } 175 176 var $preparingDialog = null; 177 178 var internalCallbacks = { 179 180 onPrepare: function (url) { 181 182 //wire up a jquery dialog to display the preparing message if specified 183 if (settings.preparingMessageHtml) { 184 185 $preparingDialog = $("<div>").html(settings.preparingMessageHtml).dialog(settings.dialogOptions); 186 187 } else if (settings.prepareCallback) { 188 189 settings.prepareCallback(url); 190 191 } 192 193 }, 194 195 onSuccess: function (url) { 196 197 //remove the perparing message if it was specified 198 if ($preparingDialog) { 199 $preparingDialog.dialog('close'); 200 } 201 202 settings.successCallback(url); 203 204 deferred.resolve(url); 205 }, 206 207 onFail: function (responseHtml, url, error) { 208 209 //remove the perparing message if it was specified 210 if ($preparingDialog) { 211 $preparingDialog.dialog('close'); 212 } 213 214 //wire up a jquery dialog to display the fail message if specified 215 if (settings.failMessageHtml) { 216 $("<div>").html(settings.failMessageHtml).dialog(settings.dialogOptions); 217 } 218 219 settings.failCallback(responseHtml, url, error); 220 221 deferred.reject(responseHtml, url); 222 } 223 }; 224 225 internalCallbacks.onPrepare(fileUrl); 226 227 //make settings.data a param string if it exists and isn't already 228 if (settings.data !== null && typeof settings.data !== "string") { 229 settings.data = $.param(settings.data); 230 } 231 232 233 var $iframe, 234 downloadWindow, 235 formDoc, 236 $form; 237 238 if (httpMethodUpper === "GET") { 239 240 if (settings.data !== null) { 241 //need to merge any fileUrl params with the data object 242 243 var qsStart = fileUrl.indexOf('?'); 244 245 if (qsStart !== -1) { 246 //we have a querystring in the url 247 248 if (fileUrl.substring(fileUrl.length - 1) !== "&") { 249 fileUrl = fileUrl + "&"; 250 } 251 } else { 252 253 fileUrl = fileUrl + "?"; 254 } 255 256 fileUrl = fileUrl + settings.data; 257 } 258 259 if (isIos || isAndroid) { 260 261 downloadWindow = window.open(fileUrl); 262 downloadWindow.document.title = settings.popupWindowTitle; 263 window.focus(); 264 265 } else if (isOtherMobileBrowser) { 266 267 window.location(fileUrl); 268 269 } else { 270 271 //create a temporary iframe that is used to request the fileUrl as a GET request 272 $iframe = $("<iframe>") 273 .hide() 274 .prop("src", fileUrl) 275 .appendTo("body"); 276 } 277 278 } else { 279 280 var formInnerHtml = ""; 281 282 if (settings.data !== null) { 283 284 $.each(settings.data.replace(/\+/g, ' ').split("&"), function () { 285 286 var kvp = this.split("="); 287 288 //Issue: When value contains sign '=' then the kvp array does have more than 2 items. We have to join value back 289 var k = kvp[0]; 290 kvp.shift(); 291 var v = kvp.join("="); 292 kvp = [k, v]; 293 294 var key = settings.encodeHTMLEntities ? htmlSpecialCharsEntityEncode(decodeURIComponent(kvp[0])) : decodeURIComponent(kvp[0]); 295 if (key) { 296 var value = settings.encodeHTMLEntities ? htmlSpecialCharsEntityEncode(decodeURIComponent(kvp[1])) : decodeURIComponent(kvp[1]); 297 formInnerHtml += '<input type="hidden" name="' + key + '" value="' + value + '" />'; 298 } 299 }); 300 } 301 302 if (isOtherMobileBrowser) { 303 304 $form = $("<form>").appendTo("body"); 305 $form.hide() 306 .prop('method', settings.httpMethod) 307 .prop('action', fileUrl) 308 .html(formInnerHtml); 309 310 } else { 311 312 if (isIos) { 313 314 downloadWindow = window.open("about:blank"); 315 downloadWindow.document.title = settings.popupWindowTitle; 316 formDoc = downloadWindow.document; 317 window.focus(); 318 319 } else { 320 321 $iframe = $("<iframe style='display: none' src='about:blank'></iframe>").appendTo("body"); 322 formDoc = getiframeDocument($iframe); 323 } 324 325 formDoc.write("<html><head></head><body><form method='" + settings.httpMethod + "' action='" + fileUrl + "'>" + formInnerHtml + "</form>" + settings.popupWindowTitle + "</body></html>"); 326 $form = $(formDoc).find('form'); 327 } 328 329 $form.submit(); 330 } 331 332 333 //check if the file download has completed every checkInterval ms 334 setTimeout(checkFileDownloadComplete, settings.checkInterval); 335 336 337 function checkFileDownloadComplete() { 338 //has the cookie been written due to a file download occuring? 339 340 var cookieValue = settings.cookieValue; 341 if(typeof cookieValue == 'string') { 342 cookieValue = cookieValue.toLowerCase(); 343 } 344 345 var lowerCaseCookie = settings.cookieName.toLowerCase() + "=" + cookieValue; 346 347 if (document.cookie.toLowerCase().indexOf(lowerCaseCookie) > -1) { 348 349 //execute specified callback 350 internalCallbacks.onSuccess(fileUrl); 351 352 //remove cookie 353 var cookieData = settings.cookieName + "=; path=" + settings.cookiePath + "; expires=" + new Date(0).toUTCString() + ";"; 354 if (settings.cookieDomain) cookieData += " domain=" + settings.cookieDomain + ";"; 355 document.cookie = cookieData; 356 357 //remove iframe 358 cleanUp(false); 359 360 return; 361 } 362 363 //has an error occured? 364 //if neither containers exist below then the file download is occuring on the current window 365 if (downloadWindow || $iframe) { 366 367 //has an error occured? 368 try { 369 370 var formDoc = downloadWindow ? downloadWindow.document : getiframeDocument($iframe); 371 372 if (formDoc && formDoc.body !== null && formDoc.body.innerHTML.length) { 373 374 var isFailure = true; 375 376 if ($form && $form.length) { 377 var $contents = $(formDoc.body).contents().first(); 378 379 try { 380 if ($contents.length && $contents[0] === $form[0]) { 381 isFailure = false; 382 } 383 } catch (e) { 384 if (e && e.number == -2146828218) { 385 // IE 8-10 throw a permission denied after the form reloads on the "$contents[0] === $form[0]" comparison 386 isFailure = true; 387 } else { 388 throw e; 389 } 390 } 391 } 392 393 if (isFailure) { 394 // IE 8-10 don't always have the full content available right away, they need a litle bit to finish 395 setTimeout(function () { 396 internalCallbacks.onFail(formDoc.body.innerHTML, fileUrl); 397 cleanUp(true); 398 }, 100); 399 400 return; 401 } 402 } 403 } 404 catch (err) { 405 406 //500 error less than IE9 407 internalCallbacks.onFail('', fileUrl, err); 408 409 cleanUp(true); 410 411 return; 412 } 413 } 414 415 416 //keep checking... 417 setTimeout(checkFileDownloadComplete, settings.checkInterval); 418 } 419 420 //gets an iframes document in a cross browser compatible manner 421 function getiframeDocument($iframe) { 422 var iframeDoc = $iframe[0].contentWindow || $iframe[0].contentDocument; 423 if (iframeDoc.document) { 424 iframeDoc = iframeDoc.document; 425 } 426 return iframeDoc; 427 } 428 429 function cleanUp(isFailure) { 430 431 setTimeout(function() { 432 433 if (downloadWindow) { 434 435 if (isAndroid) { 436 downloadWindow.close(); 437 } 438 439 if (isIos) { 440 if (downloadWindow.focus) { 441 downloadWindow.focus(); //ios safari bug doesn't allow a window to be closed unless it is focused 442 if (isFailure) { 443 downloadWindow.close(); 444 } 445 } 446 } 447 } 448 449 //iframe cleanup appears to randomly cause the download to fail 450 //not doing it seems better than failure... 451 //if ($iframe) { 452 // $iframe.remove(); 453 //} 454 455 }, 0); 456 } 457 458 459 function htmlSpecialCharsEntityEncode(str) { 460 return str.replace(htmlSpecialCharsRegEx, function(match) { 461 return '&' + htmlSpecialCharsPlaceHolders[match]; 462 }); 463 } 464 var promise = deferred.promise(); 465 promise.abort = function() { 466 cleanUp(); 467 $iframe.remove(); 468 }; 469 return promise; 470 } 471}); 472 473})(jQuery, this); 474