[IMP] web: replace iframe-based get_file by XHR
The error handling in get_file has always been somewhat problematic (sarcasm ho!). Pending PR #24854 attempts to add special handling for gateway timeout aside from its base stuff, and that's really quite terrible due to get_file's limitation of only being able to read the content of the document loaded in the iframe (no proper access to status codes & al). That was the occasion to look up modern API and see if we could do file downloads in JS without iframe crap. Turns out we can: xhr2 is well supported so we can POST, get a blob back, and create a "local download" for that in-memory blob using either a[download] (most browsers) or msSaveBlob (IE10+, that's actually a convenient-to-great API and it's a shame there's nothing like it in the standard). The changes are not trivial but save ~30LOC and most of the overhead is replicating the old/weird error handling as that requires additionally decoding the blob to a string & parsing that string to a document before being able to get the content (whereas before we'd just access to the document loaded in the iframe). OTOH we can now properly forward non-200 status codes to the crash manager (as name) which will allow using regular CM hooks to provide custom warning and error messages. Note that this requires two libraries: * a stripped down version of the content-disposition NPM lib, as download file names are provided via that header and parsing the header is decidedly non-trivial * the download.js library as it handles the various edge cases from different browsers, I'm don't think all of it is necessary for our use case but the library is not that big so no real point in trying to strip it out and potentially break it in the process
This commit is contained in:
@@ -4,6 +4,10 @@ odoo.define('web.ajax', function (require) {
|
||||
var core = require('web.core');
|
||||
var utils = require('web.utils');
|
||||
var time = require('web.time');
|
||||
var download = require('web.download');
|
||||
var contentdisposition = require('web.contentdisposition');
|
||||
|
||||
var _t = core._t;
|
||||
|
||||
function genericJsonRpc (fct_name, params, settings, fct) {
|
||||
var shadow = settings.shadow || false;
|
||||
@@ -269,120 +273,85 @@ var loadJS = (function () {
|
||||
* changed to make it work.
|
||||
*/
|
||||
function get_file(options) {
|
||||
// need to detect when the file is done downloading (not used
|
||||
// yet, but we'll need it to fix the UI e.g. with a throbber
|
||||
// while dump is being generated), iframe load event only fires
|
||||
// when the iframe content loads, so we need to go smarter:
|
||||
// http://geekswithblogs.net/GruffCode/archive/2010/10/28/detecting-the-file-download-dialog-in-the-browser.aspx
|
||||
var timer, token = new Date().getTime(),
|
||||
cookie_name = 'fileToken', cookie_length = cookie_name.length,
|
||||
CHECK_INTERVAL = 1000, id = _.uniqueId('get_file_frame'),
|
||||
remove_form = false;
|
||||
|
||||
|
||||
// iOS devices doesn't allow iframe use the way we do it,
|
||||
// opening a new window seems the best way to workaround
|
||||
if (navigator.userAgent.match(/(iPod|iPhone|iPad)/)) {
|
||||
var params = _.extend({}, options.data || {}, {token: token});
|
||||
var url = options.session.url(options.url, params);
|
||||
if (options.complete) { options.complete(); }
|
||||
|
||||
var w = window.open(url);
|
||||
if (!w || w.closed || typeof w.closed === 'undefined') {
|
||||
// popup was blocked
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
var $form, $form_data = $('<div>');
|
||||
|
||||
var complete = function () {
|
||||
if (options.complete) { options.complete(); }
|
||||
clearTimeout(timer);
|
||||
$form_data.remove();
|
||||
$target.remove();
|
||||
if (remove_form && $form) { $form.remove(); }
|
||||
};
|
||||
var $target = $('<iframe style="display: none;">')
|
||||
.attr({id: id, name: id})
|
||||
.appendTo(document.body)
|
||||
.load(function () {
|
||||
try {
|
||||
if (options.error) {
|
||||
var body = this.contentDocument.body;
|
||||
var nodes = body.children.length === 0 ? body.childNodes : body.children;
|
||||
var errorParams = {};
|
||||
|
||||
try { // Case of a serialized Odoo Exception: It is Json Parsable
|
||||
var node = nodes[1] || nodes[0];
|
||||
errorParams = JSON.parse(node.textContent);
|
||||
} catch (e) { // Arbitrary uncaught python side exception
|
||||
errorParams = {
|
||||
message: nodes.length > 1 ? nodes[1].textContent : '',
|
||||
data: {
|
||||
title: nodes.length > 0 ? nodes[0].textContent : '',
|
||||
}
|
||||
}
|
||||
}
|
||||
options.error(errorParams);
|
||||
}
|
||||
} finally {
|
||||
complete();
|
||||
}
|
||||
});
|
||||
var xhr = new XMLHttpRequest();
|
||||
|
||||
var data;
|
||||
if (options.form) {
|
||||
$form = $(options.form);
|
||||
xhr.open(options.form.method, options.form.action);
|
||||
data = new FormData(options.form);
|
||||
} else {
|
||||
remove_form = true;
|
||||
$form = $('<form>', {
|
||||
action: options.url,
|
||||
method: 'POST'
|
||||
}).appendTo(document.body);
|
||||
}
|
||||
if (core.csrf_token) {
|
||||
$('<input type="hidden" name="csrf_token">')
|
||||
.val(core.csrf_token)
|
||||
.appendTo($form_data);
|
||||
}
|
||||
|
||||
var hparams = _.extend({}, options.data || {}, {token: token});
|
||||
_.each(hparams, function (value, key) {
|
||||
var $input = $form.find('[name=' + key +']');
|
||||
if (!$input.length) {
|
||||
$input = $('<input type="hidden" name="' + key + '">')
|
||||
.appendTo($form_data);
|
||||
}
|
||||
$input.val(value);
|
||||
xhr.open('POST', options.url);
|
||||
data = new FormData();
|
||||
_.each(options.data || {}, function (v, k) {
|
||||
data.append(k, v)
|
||||
});
|
||||
}
|
||||
data.append('token', 'dummy-because-api-expects-one');
|
||||
if (core.csrf_token) {
|
||||
data.append('csrf_token', core.csrf_token);
|
||||
}
|
||||
// IE11 wants this after xhr.open or it throws
|
||||
xhr.responseType = 'blob';
|
||||
|
||||
$form
|
||||
.append($form_data)
|
||||
.attr('target', id)
|
||||
.get(0).submit();
|
||||
// onreadystatechange[readyState = 4]
|
||||
// => onload (success) | onerror (error) | onabort
|
||||
// => onloadend
|
||||
xhr.onload = function () {
|
||||
var mimetype = xhr.response.type;
|
||||
if (xhr.status === 200 && mimetype !== 'text/html') {
|
||||
// replace because apparently we send some C-D headers with a trailing ";"
|
||||
// todo: maybe a lack of CD[attachment] should be interpreted as an error case?
|
||||
var header = (xhr.getResponseHeader('Content-Disposition') || '').replace(/;$/, '');
|
||||
var filename = header ? contentdisposition.parse(header).parameters.filename : null;
|
||||
|
||||
var waitLoop = function () {
|
||||
var cookies = document.cookie.split(';');
|
||||
// setup next check
|
||||
timer = setTimeout(waitLoop, CHECK_INTERVAL);
|
||||
for (var i=0; i<cookies.length; ++i) {
|
||||
var cookie = cookies[i].replace(/^\s*/, '');
|
||||
if (!cookie.indexOf(cookie_name === 0)) { continue; }
|
||||
var cookie_val = cookie.substring(cookie_length + 1);
|
||||
if (parseInt(cookie_val, 10) !== token) { continue; }
|
||||
|
||||
// clear cookie
|
||||
document.cookie = _.str.sprintf("%s=;expires=%s;path=/",
|
||||
cookie_name, new Date().toGMTString());
|
||||
download(xhr.response, filename, mimetype);
|
||||
// not sure download is going to be sync so this may be called
|
||||
// before the file is actually fetched (?)
|
||||
if (options.success) { options.success(); }
|
||||
complete();
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!options.error) {
|
||||
return true;
|
||||
}
|
||||
var decoder = new FileReader();
|
||||
decoder.onload = function () {
|
||||
var contents = decoder.result;
|
||||
|
||||
var err;
|
||||
var doc = new DOMParser().parseFromString(contents, 'text/html');
|
||||
var nodes = doc.body.children.length === 0 ? doc.body.childNodes : doc.body.children;
|
||||
try { // Case of a serialized Odoo Exception: It is Json Parsable
|
||||
var node = nodes[1] || nodes[0];
|
||||
err = JSON.parse(node.textContent);
|
||||
} catch (e) { // Arbitrary uncaught python side exception
|
||||
err = {
|
||||
message: nodes.length > 1 ? nodes[1].textContent : '',
|
||||
data: {
|
||||
name: String(xhr.status),
|
||||
title: nodes.length > 0 ? nodes[0].textContent : '',
|
||||
}
|
||||
}
|
||||
}
|
||||
options.error(err);
|
||||
};
|
||||
decoder.readAsText(xhr.response);
|
||||
};
|
||||
xhr.onerror = function () {
|
||||
if (options.error) {
|
||||
options.error({
|
||||
message: _("Something happened while trying to contact the server, check that the server is online and that you still have a working network connection."),
|
||||
data: { title: _t("Could not connect to the server") }
|
||||
});
|
||||
}
|
||||
};
|
||||
timer = setTimeout(waitLoop, CHECK_INTERVAL);
|
||||
if (options.complete) {
|
||||
xhr.onloadend = function () { options.complete(); }
|
||||
}
|
||||
|
||||
xhr.send(data);
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
function post (controller_url, data) {
|
||||
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
/*
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2014-2017 Douglas Christopher Wilson
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
'Software'), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
||||
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Stripped down to only parsing/decoding.
|
||||
*/
|
||||
odoo.define('web.contentdisposition', function () {
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* RegExp to match percent encoding escape.
|
||||
* @private
|
||||
*/
|
||||
var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g;
|
||||
|
||||
/**
|
||||
* RegExp to match non-latin1 characters.
|
||||
* @private
|
||||
*/
|
||||
var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g;
|
||||
|
||||
/**
|
||||
* RegExp to match quoted-pair in RFC 2616
|
||||
*
|
||||
* quoted-pair = "\" CHAR
|
||||
* CHAR = <any US-ASCII character (octets 0 - 127)>
|
||||
* @private
|
||||
*/
|
||||
var QESC_REGEXP = /\\([\u0000-\u007f])/g;
|
||||
|
||||
/**
|
||||
* RegExp for various RFC 2616 grammar
|
||||
*
|
||||
* parameter = token "=" ( token | quoted-string )
|
||||
* token = 1*<any CHAR except CTLs or separators>
|
||||
* separators = "(" | ")" | "<" | ">" | "@"
|
||||
* | "," | ";" | ":" | "\" | <">
|
||||
* | "/" | "[" | "]" | "?" | "="
|
||||
* | "{" | "}" | SP | HT
|
||||
* quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
|
||||
* qdtext = <any TEXT except <">>
|
||||
* quoted-pair = "\" CHAR
|
||||
* CHAR = <any US-ASCII character (octets 0 - 127)>
|
||||
* TEXT = <any OCTET except CTLs, but including LWS>
|
||||
* LWS = [CRLF] 1*( SP | HT )
|
||||
* CRLF = CR LF
|
||||
* CR = <US-ASCII CR, carriage return (13)>
|
||||
* LF = <US-ASCII LF, linefeed (10)>
|
||||
* SP = <US-ASCII SP, space (32)>
|
||||
* HT = <US-ASCII HT, horizontal-tab (9)>
|
||||
* CTL = <any US-ASCII control character (octets 0 - 31) and DEL (127)>
|
||||
* OCTET = <any 8-bit sequence of data>
|
||||
* @private
|
||||
*/
|
||||
var PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g;
|
||||
|
||||
/**
|
||||
* RegExp for various RFC 5987 grammar
|
||||
*
|
||||
* ext-value = charset "'" [ language ] "'" value-chars
|
||||
* charset = "UTF-8" / "ISO-8859-1" / mime-charset
|
||||
* mime-charset = 1*mime-charsetc
|
||||
* mime-charsetc = ALPHA / DIGIT
|
||||
* / "!" / "#" / "$" / "%" / "&"
|
||||
* / "+" / "-" / "^" / "_" / "`"
|
||||
* / "{" / "}" / "~"
|
||||
* language = ( 2*3ALPHA [ extlang ] )
|
||||
* / 4ALPHA
|
||||
* / 5*8ALPHA
|
||||
* extlang = *3( "-" 3ALPHA )
|
||||
* value-chars = *( pct-encoded / attr-char )
|
||||
* pct-encoded = "%" HEXDIG HEXDIG
|
||||
* attr-char = ALPHA / DIGIT
|
||||
* / "!" / "#" / "$" / "&" / "+" / "-" / "."
|
||||
* / "^" / "_" / "`" / "|" / "~"
|
||||
* @private
|
||||
*/
|
||||
var EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/;
|
||||
|
||||
/**
|
||||
* RegExp for various RFC 6266 grammar
|
||||
*
|
||||
* disposition-type = "inline" | "attachment" | disp-ext-type
|
||||
* disp-ext-type = token
|
||||
* disposition-parm = filename-parm | disp-ext-parm
|
||||
* filename-parm = "filename" "=" value
|
||||
* | "filename*" "=" ext-value
|
||||
* disp-ext-parm = token "=" value
|
||||
* | ext-token "=" ext-value
|
||||
* ext-token = <the characters in token, followed by "*">
|
||||
* @private
|
||||
*/
|
||||
var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/;
|
||||
|
||||
/**
|
||||
* Decode a RFC 6987 field value (gracefully).
|
||||
*
|
||||
* @param {string} str
|
||||
* @return {string}
|
||||
* @private
|
||||
*/
|
||||
function decodefield(str) {
|
||||
var match = EXT_VALUE_REGEXP.exec(str);
|
||||
|
||||
if (!match) {
|
||||
throw new TypeError('invalid extended field value')
|
||||
}
|
||||
|
||||
var charset = match[1].toLowerCase();
|
||||
var encoded = match[2];
|
||||
|
||||
switch (charset) {
|
||||
case 'iso-8859-1':
|
||||
return encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode).replace(NON_LATIN1_REGEXP, '?');
|
||||
case 'utf-8':
|
||||
return decodeURIComponent(encoded);
|
||||
default:
|
||||
throw new TypeError('unsupported charset in extended field')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse Content-Disposition header string.
|
||||
*
|
||||
* @param {string} string
|
||||
* @return {ContentDisposition}
|
||||
* @public
|
||||
*/
|
||||
function parse(string) {
|
||||
if (!string || typeof string !== 'string') {
|
||||
throw new TypeError('argument string is required')
|
||||
}
|
||||
|
||||
var match = DISPOSITION_TYPE_REGEXP.exec(string);
|
||||
|
||||
if (!match) {
|
||||
throw new TypeError('invalid type format')
|
||||
}
|
||||
|
||||
// normalize type
|
||||
var index = match[0].length;
|
||||
var type = match[1].toLowerCase();
|
||||
|
||||
var key;
|
||||
var names = [];
|
||||
var params = {};
|
||||
var value;
|
||||
|
||||
// calculate index to start at
|
||||
index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ';' ? index - 1 : index;
|
||||
|
||||
// match parameters
|
||||
while ((match = PARAM_REGEXP.exec(string))) {
|
||||
if (match.index !== index) {
|
||||
throw new TypeError('invalid parameter format')
|
||||
}
|
||||
|
||||
index += match[0].length;
|
||||
key = match[1].toLowerCase();
|
||||
value = match[2];
|
||||
|
||||
if (names.indexOf(key) !== -1) {
|
||||
throw new TypeError('invalid duplicate parameter')
|
||||
}
|
||||
|
||||
names.push(key);
|
||||
|
||||
if (key.indexOf('*') + 1 === key.length) {
|
||||
// decode extended value
|
||||
key = key.slice(0, -1);
|
||||
value = decodefield(value);
|
||||
|
||||
// overwrite existing value
|
||||
params[key] = value;
|
||||
continue
|
||||
}
|
||||
|
||||
if (typeof params[key] === 'string') {
|
||||
continue
|
||||
}
|
||||
|
||||
if (value[0] === '"') {
|
||||
// remove quotes and escapes
|
||||
value = value
|
||||
.substr(1, value.length - 2)
|
||||
.replace(QESC_REGEXP, '$1')
|
||||
}
|
||||
|
||||
params[key] = value
|
||||
}
|
||||
|
||||
if (index !== -1 && index !== string.length) {
|
||||
throw new TypeError('invalid parameter format')
|
||||
}
|
||||
|
||||
return new ContentDisposition(type, params)
|
||||
}
|
||||
|
||||
/**
|
||||
* Percent decode a single character.
|
||||
*
|
||||
* @param {string} str
|
||||
* @param {string} hex
|
||||
* @return {string}
|
||||
* @private
|
||||
*/
|
||||
function pdecode(str, hex) {
|
||||
return String.fromCharCode(parseInt(hex, 16))
|
||||
}
|
||||
|
||||
/**
|
||||
* Class for parsed Content-Disposition header for v8 optimization
|
||||
*
|
||||
* @public
|
||||
* @param {string} type
|
||||
* @param {object} parameters
|
||||
* @constructor
|
||||
*/
|
||||
function ContentDisposition(type, parameters) {
|
||||
this.type = type;
|
||||
this.parameters = parameters
|
||||
}
|
||||
|
||||
return {
|
||||
parse: parse,
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,153 @@
|
||||
/*
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2016 dandavis
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
*/
|
||||
|
||||
/**
|
||||
* download.js v4.2, by dandavis; 2008-2018. [MIT] see http://danml.com/download.html for tests/usage
|
||||
*
|
||||
* @param {Blob | File | String} data
|
||||
* @param {String} [filename]
|
||||
* @param {String} [mimetype]
|
||||
*/
|
||||
odoo.define('web.download', function () {
|
||||
return function download(data, filename, mimetype) {
|
||||
var self = window, // this script is only for browsers anyway...
|
||||
defaultMime = "application/octet-stream", // this default mime also triggers iframe downloads
|
||||
mimeType = mimetype || defaultMime, payload = data,
|
||||
url = !filename && !mimetype && payload,
|
||||
anchor = document.createElement("a"),
|
||||
toString = function (a) {return String(a);},
|
||||
myBlob = (self.Blob || self.MozBlob || self.WebKitBlob || toString),
|
||||
fileName = filename || "download", blob, reader;
|
||||
myBlob = myBlob.call ? myBlob.bind(self) : Blob;
|
||||
|
||||
if (String(this) === "true") { //reverse arguments, allowing download.bind(true, "text/xml", "export.xml") to act as a callback
|
||||
payload = [payload, mimeType];
|
||||
mimeType = payload[0];
|
||||
payload = payload[1];
|
||||
}
|
||||
|
||||
if (url && url.length < 2048) { // if no filename and no mime, assume a url was passed as the only argument
|
||||
fileName = url.split("/").pop().split("?")[0];
|
||||
anchor.href = url; // assign href prop to temp anchor
|
||||
if (anchor.href.indexOf(url) !== -1) { // if the browser determines that it's a potentially valid url path:
|
||||
var ajax = new XMLHttpRequest();
|
||||
ajax.open("GET", url, true);
|
||||
ajax.responseType = 'blob';
|
||||
ajax.onload = function (e) {
|
||||
download(e.target.response, fileName, defaultMime);
|
||||
};
|
||||
setTimeout(function () { ajax.send();}, 0); // allows setting custom ajax headers using the return:
|
||||
return ajax;
|
||||
}
|
||||
}
|
||||
|
||||
//go ahead and download dataURLs right away
|
||||
if (/^data:[\w+\-]+\/[\w+\-]+[,;]/.test(payload)) {
|
||||
|
||||
if (payload.length > (1024 * 1024 * 1.999) && myBlob !== toString) {
|
||||
payload = dataUrlToBlob(payload);
|
||||
mimeType = payload.type || defaultMime;
|
||||
} else {
|
||||
return navigator.msSaveBlob ? // IE10 can't do a[download], only Blobs:
|
||||
navigator.msSaveBlob(dataUrlToBlob(payload), fileName) : saver(payload); // everyone else can save dataURLs un-processed
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
blob = payload instanceof myBlob ? payload : new myBlob([payload], {type: mimeType});
|
||||
|
||||
|
||||
function dataUrlToBlob(strUrl) {
|
||||
var parts = strUrl.split(/[:;,]/), type = parts[1],
|
||||
decoder = parts[2] === "base64" ? atob : decodeURIComponent,
|
||||
binData = decoder(parts.pop()), mx = binData.length,
|
||||
i = 0, uiArr = new Uint8Array(mx);
|
||||
|
||||
for (i; i < mx; ++i) uiArr[i] = binData.charCodeAt(i);
|
||||
|
||||
return new myBlob([uiArr], {type: type});
|
||||
}
|
||||
|
||||
function saver(url, winMode) {
|
||||
if ('download' in anchor) { //html5 A[download]
|
||||
anchor.href = url;
|
||||
anchor.setAttribute("download", fileName);
|
||||
anchor.className = "download-js-link";
|
||||
anchor.innerHTML = "downloading...";
|
||||
anchor.style.display = "none";
|
||||
document.body.appendChild(anchor);
|
||||
setTimeout(function () {
|
||||
anchor.click();
|
||||
document.body.removeChild(anchor);
|
||||
if (winMode === true) {setTimeout(function () { self.URL.revokeObjectURL(anchor.href);}, 250);}
|
||||
}, 66);
|
||||
return true;
|
||||
}
|
||||
|
||||
// handle non-a[download] safari as best we can:
|
||||
if (/(Version)\/(\d+)\.(\d+)(?:\.(\d+))?.*Safari\//.test(navigator.userAgent)) {
|
||||
url = url.replace(/^data:([\w\/\-+]+)/, defaultMime);
|
||||
if (!window.open(url)) { // popup blocked, offer direct download:
|
||||
if (confirm("Displaying New Document\n\nUse Save As... to download, then click back to return to this page.")) { location.href = url; }
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
//do iframe dataURL download (old ch+FF):
|
||||
var f = document.createElement("iframe");
|
||||
document.body.appendChild(f);
|
||||
|
||||
if (!winMode) { // force a mime that will download:
|
||||
url = "data:" + url.replace(/^data:([\w\/\-+]+)/, defaultMime);
|
||||
}
|
||||
f.src = url;
|
||||
setTimeout(function () { document.body.removeChild(f); }, 333);
|
||||
}
|
||||
|
||||
if (navigator.msSaveBlob) { // IE10+ : (has Blob, but not a[download] or URL)
|
||||
return navigator.msSaveBlob(blob, fileName);
|
||||
}
|
||||
|
||||
if (self.URL) { // simple fast and modern way using Blob and URL:
|
||||
saver(self.URL.createObjectURL(blob), true);
|
||||
} else {
|
||||
// handle non-Blob()+non-URL browsers:
|
||||
if (typeof blob === "string" || blob.constructor === toString) {
|
||||
try {
|
||||
return saver("data:" + mimeType + ";base64," + self.btoa(blob));
|
||||
} catch (y) {
|
||||
return saver("data:" + mimeType + "," + encodeURIComponent(blob));
|
||||
}
|
||||
}
|
||||
|
||||
// Blob but not URL support:
|
||||
reader = new FileReader();
|
||||
reader.onload = function () {
|
||||
saver(this.result);
|
||||
};
|
||||
reader.readAsDataURL(blob);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
});
|
||||
@@ -90,6 +90,8 @@
|
||||
<script type="text/javascript" src="/web/static/src/js/libs/autocomplete.js"></script>
|
||||
<script type="text/javascript" src="/web/static/src/js/libs/bootstrap.js"></script>
|
||||
<script type="text/javascript" src="/web/static/src/js/libs/jquery.js"></script>
|
||||
<script type="text/javascript" src="/web/static/src/js/libs/download.js"></script>
|
||||
<script type="text/javascript" src="/web/static/src/js/libs/content-disposition.js"></script>
|
||||
<script type="text/javascript" src="/web/static/src/js/services/config.js"></script>
|
||||
<script type="text/javascript" src="/web/static/src/js/core/abstract_service.js"></script>
|
||||
<script type="text/javascript" src="/web/static/src/js/core/abstract_storage_service.js"></script>
|
||||
|
||||
Reference in New Issue
Block a user