I am trying to add the functionality to download a file hosted in a server. To access the file I have to send the Authorization header, thus I have to send an XHR request to get the file from the server. Since the file content is in a variable, I have to create a data url to make it available as the href attribute of an anchor tag and click it programmatically to download the file.
It's working good in almost all the browser (Except IE11, for which I have written a separate code), but in iOS Safari (in some versions of iOS), it's giving errors. Here's the code that I am using -
var isBrowserIE = window.navigator && window.navigator.msSaveOrOpenBlob;
var dataHref = 'https://example.com/doc.pdf';
var xhr = new XMLHttpRequest();
xhr.open('GET', dataHref, true);
xhr.setRequestHeader('Content-Type', 'application/pdf');
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
xhr.responseType = isBrowserIE ? 'blob' : 'arraybuffer';
xhr.onload = function (e) {
if (this.status == 200) {
//For IE11
if (isBrowserIE) {
// Create a new Blob object using the response data of the onload object
var blob = new Blob([this.response], { type: 'application/pdf' });
var bool = window.navigator.msSaveOrOpenBlob(blob, docName);
if (!bool) {
alert("Download failed, Please try again later");
}
} else {
var uInt8Array = new Uint8Array(this.response);
var i = uInt8Array.length;
var binaryString = new Array(i);
while (i--) {
binaryString[i] = String.fromCharCode(uInt8Array[i]);
}
var data = binaryString.join('');
var base64 = window.btoa(data);
var dataUrl = 'data:application/octet-stream;charset=utf-16le;base64,' + base64;
var element = document.createElement('a');
element.setAttribute('href', dataUrl);
element.setAttribute('download', 'doc.pdf');
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
} else {
alert("Download failed, Please try again later");
closeWindow();
}
};
xhr.send();
Here's the possible error I am getting which is related -
Safari cannot open the page.<br><br>The error was: “Data URL decoding failed”.
Is there anything I missed which is the reason for this error? The error is occuring only in iPad 4 and iPad 5, but working in iPad mini and iPhone XR. Not sure why is it working in some versions of iOS devices and not in others.
So, I finally figured it out. Here's my final code with explanations in comments (Sorry for ES5 code, I needed to support IE11 and the current project is not using babel yet) -
/* exported DownloadHandler */
/* global Uint8Array*/
var DownloadHandler = (function() {
function isMobileDevice() {
return navigator.userAgent.match(/Android|iPhone|iPad|iPod|BlackBerry|Opera Mini|IEMobile/i);
}
function isChromeBrowser() {
return navigator.userAgent.match(/Crios|Chrome/i);
}
function isIEBrowser() {
return window.navigator && window.navigator.msSaveOrOpenBlob;
}
function isSafariBrowser() {
return navigator.userAgent.match(/Safari/i);
}
function getResponseType() {
// Both Desktop Chrome and IE supports blob properly
// Chrome also supports Data URI way, but it fails miserably when the file size is more than 2 MB (Not sure about the exact limit though).
if (isIEBrowser() || isChromeBrowser()) {
return 'blob';
} else if (isMobileDevice()) {
return 'arraybuffer';
}
return 'blob';
}
function getBlobUriFromResponse(response) {
var blob = new Blob([response], { type: 'application/pdf' });
var downloadUrl = URL.createObjectURL(blob);
return downloadUrl;
}
function getDataUriFromResponse(response) {
var uInt8Array = new Uint8Array(response);
var i = uInt8Array.length;
var binaryString = new Array(i);
while (i--) {
binaryString[i] = String.fromCharCode(uInt8Array[i]);
}
var data = binaryString.join('');
var base64 = window.btoa(data);
var dataUrl = 'data:application/octet-stream;charset=utf-16le;base64,' + base64;
return dataUrl;
}
function downloadFileUsingXHR(fileName, fileUrl, fileMimeType, requestType, headersList) {
var xhr = new XMLHttpRequest();
xhr.open(requestType, fileUrl, true);
xhr.setRequestHeader('Content-Type', fileMimeType);
for (var i = 0; i < headersList.length; i++) {
var header = headersList[i];
xhr.setRequestHeader(header.key, header.value);
}
xhr.responseType = getResponseType();
xhr.onload = function() {
if (this.status == 200) {
//For IE11
//IE uses blob with vendor specific code
if (isIEBrowser()) {
// Create a new Blob object using the response data of the onload object
var blob = new Blob([this.response], { type: fileMimeType });
var bool = window.navigator.msSaveOrOpenBlob(blob, fileName);
if (!bool) {
alert('Download failed, Please try again later');
}
} else {
var dataUrl;
if (this.responseType === 'blob') {
dataUrl = getBlobUriFromResponse(this.response);
} else {
dataUrl = getDataUriFromResponse(this.response);
}
var element = document.createElement('a');
// Safari doesn't work well with blank targets
if (!isSafariBrowser()) {
element.setAttribute('target', '_blank');
}
element.setAttribute('href', dataUrl);
element.setAttribute('download', fileName);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
} else {
alert('Download failed, Please try again later');
}
};
xhr.send();
}
return {
downloadFileUsingXHR: downloadFileUsingXHR
};
})();
Here's how to use the above code:
DownloadHandler.downloadFileUsingXHR('example.pdf', 'https://example.com/doc.pdf', 'application/pdf','GET',[{key:'Authorization',value:'Bearer ' + token}]);
I'll probably convert it into a library later and post a link here. I'll get the chance to refine the code too
Related
My api call requires me to pass the api key in the headers, but I'm getting error back from the api service {"error":"2424452","message":"Invalid Api Key"}
I know my api key is valid as I can make the same api call in Python just fine, example:
req = requests.Session()
req.headers.update({'x-api-key': 'my-api-key', 'X-Product': 'my-product-name'})
req.get(url)
But in javscript, the same call errors out. I believe I'm not setting the headers correctly or something?
var req = new XMLHttpRequest();
req.onreadystatechange=handleStateChange;
req.open("GET", "url", true);
req.setRequestHeader("Host", "api.domain.com", "x-api-key", "my-api-key", "X-Product", "my-product-name");
req.send();
This XMLHttpRequest is not a browser call, rather in an application that support XMLHttpRequest.
setRequestHeader sets one header and takes two arguments (the name and the value).
If you want to set multiple headers, then call setRequestHeader multiple times. Don't add extra arguments to the first call.
In case you don't want to set multiple headers explicitly you can use
function setHeaders(headers){
for(let key in headers){
xhr.setRequestHeader(key, headers[key])
}
}
setHeaders({"Host":"api.domain.com","X-Requested-With":"XMLHttpRequest","contentType":"application/json"})
downloadReportFile(id, query): Observable<Object[]> {
var url = `${environment.baseUrl}report?report_name=${id}${query}`;
return Observable.create(observer => {
let xhr = new XMLHttpRequest();
xhr.open('GET', `${url}`, true);
xhr.setRequestHeader(environment.AUTH_TOKEN_HEADER_KEY, 'Bearer '+
localStorage.getItem(environment.AUTH_TOKEN_STORE_KEY));
xhr.responseType = 'blob';
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
let filename = "Claim_Report.csv"
var contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
var blob = new Blob([xhr.response], { type: "text/plain;charset=utf-8" });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(blob, filename);
return;
}
const blobURL = window.URL.createObjectURL(blob);
const tempLink = document.createElement('a');
tempLink.style.display = 'none';
tempLink.href = blobURL;
tempLink.setAttribute('download', filename);
if (typeof tempLink.download === 'undefined') {
tempLink.setAttribute('target', '_blank');
}
document.body.appendChild(tempLink);
tempLink.click();
document.body.removeChild(tempLink);
setTimeout(() => {
// For Firefox it is necessary to delay revoking the ObjectURL
window.URL.revokeObjectURL(blobURL);
}, 100);
} else {
observer.error(xhr.response);
}
}
}
xhr.send();
});
}
I using MediaRecorder to record microphone. The default format of MediaRecorder in chrome is video/webm. Here is short example:
navigator.mediaDevices.getUserMedia({audio: true,video: false})
.then(function(stream) {
var recordedChunks = [];
var recorder = new MediaRecorder(stream);
recorder.start(10);
recorder.ondataavailable = function (event) {
if (event.data.size > 0) {
recordedChunks.push(event.data);
} else {
// ...
}
}
setTimeout(function(){
recorder.stop();
var blob = new Blob(recordedChunks, {
"type": recordedChunks[0].type
});
var blobUrl = URL.createObjectURL(blob);
var context = new AudioContext();
var request = new XMLHttpRequest();
request.open("GET", blobUrl, true);
request.responseType = "arraybuffer";
request.onload = function () {
context.decodeAudioData(
request.response,
function (buffer) {
if (!buffer) {
alert("buffer is empty!");
}
var dataArray = buffer.getChannelData(0);
//process channel data...
context.close();
},
function (error) {
alert(error);
}
);
};
request.send();
}, 3000);
})
.catch(function(error) {
console.log('error: ' + error);
});
This code is trow error of "Uncaught (in promise) DOMException: Unable to decode audio data" on context.decodeAudioData in chrome only.
What is wrong here and how can i fix it in chrome?
Here is working example in plunker: plunker
Ok... There is no fix for the issue. This is a chrome bug and you can see it here
The fix of decoding audio from MediaRecorder will be available on chrome version 58. I already tested it on 58-beta and it works.
I have a downloading problem in Google Chrome.
I am using Ruby 2.2, Rails 4.2, AngularJS 1.2.
We dont have a database here. Everything we are getting through API. The file which we are trying to download is around 7 mb. It gives us "Failed: Network Error". Though it works fine on Firefox.
From the API we are getting binary data in JSON. We are parsing it. And then:
send_data response_fields["attachment"], type: response_fields["mimeType"], disposition: 'attachment', filename: params[:filename]
As we are using AngularJS, we are catching that value in AngularJS Controller and then converting it as:
var str = data;
var uri = "data:" + mimeType + ";base64," + str;
var downloadLink = document.createElement("a");
downloadLink.href = uri;
downloadLink.download = filename;
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
This works in Firefox & even Chrome for smaller file size. Not sure why it is giving error for bigger size on Chrome.
Any suggestions?
Thanks.
This is an almost duplicate of these questions 1 and 2, but since they do deal particularly with the canvas element, I'll rewrite a more global solution here.
This problem is due to a size limit chrome has set in the anchor (<a>) download attribute. I'm not quite sure why they did it, but the solution is pretty easy.
Convert your dataURI to a Blob, then create an ObjectURL from this Blob, and pass this ObjectURL as the anchor's download attribute.
// edited from https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob#Polyfill
function dataURIToBlob(dataURI) {
var binStr = atob(dataURI.split(',')[1]),
len = binStr.length,
arr = new Uint8Array(len),
mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
for (var i = 0; i < len; i++) {
arr[i] = binStr.charCodeAt(i);
}
return new Blob([arr], {
type: mimeString
});
}
var dataURI_DL = function() {
var dataURI = this.result;
var blob = dataURIToBlob(dataURI);
var url = URL.createObjectURL(blob);
var blobAnchor = document.getElementById('blob');
var dataURIAnchor = document.getElementById('dataURI');
blobAnchor.download = dataURIAnchor.download = 'yourFile.mp4';
blobAnchor.href = url;
dataURIAnchor.href = dataURI;
stat_.textContent = '';
blobAnchor.onclick = function() {
requestAnimationFrame(function() {
URL.revokeObjectURL(url);
})
};
};
// That may seem stupid, but for the sake of the example, we'll first convert a blob to a dataURI...
var start = function() {
stat_.textContent = 'Please wait while loading...';
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
status.textContent = 'converting';
var fr = new FileReader();
fr.onload = dataURI_DL;
fr.readAsDataURL(this.response);
};
xhr.open('GET', 'https://dl.dropboxusercontent.com/s/bch2j17v6ny4ako/movie720p.mp4?dl=0');
xhr.send();
confirm_btn.parentNode.removeChild(confirm_btn);
};
confirm_btn.onclick = start;
<button id="confirm_btn">Start the loading of this 45Mb video</button>
<span id="stat_"></span>
<br>
<a id="blob">blob</a>
<a id="dataURI">dataURI</a>
And a jsfiddle version for FF, since they don't allow the downloadattribute from stack-snippets...
I'm getting a file from a server with AJAX (Angular).The file is a simple XLSX document, sent like this:
ob_start();
$file = \PHPExcel_IOFactory::createWriter($xls, 'Excel2007');
$file->save('php://output');
$response->setContent(ob_get_clean());
$response->headers->replace(array(
'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'Content-Disposition' => 'attachment;filename=file.xlsx"'
));
When I make a request from frontend, I use Accept header too. Then I save the file with angular-file-saver using FileSaver.js and Blob.js.
But the received file is corrupt and I can't open it in Excel: it's size is (for example) 12446 bytes, but Chrome's DevTools Network tab shows responses Content-Length header as 7141 bytes.
How can I solve this problem?
UPD:
I'm sending a request like this:
$http.get(baseURL + '/' + entity + '/export/?' + condition + sort, {
headers: {'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=utf-8'}
});
and downloading file just like this:
var data = new Blob([response.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'});
FileSaver.saveAs(data, 'file.xlsx');
The way I got around the problem was using plain JS AJAX, instead of AngularJS. (There might be a problem with AngularJS and JQuery handling binary responses.)
This should work:
var request = new XMLHttpRequest();
request.open('GET', 'http://yourserver/yourpath', true);
request.responseType = 'blob';
request.onload = function (e) {
if (this.status === 200) {
var blob = this.response;
if (window.navigator.msSaveOrOpenBlob) {
var fileNamePattern = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
window.navigator.msSaveBlob(blob, fileNamePattern.exec(request.getResponseHeader("content-disposition"))[1]);
} else {
var downloadLink = window.document.createElement('a');
var contentTypeHeader = request.getResponseHeader("Content-Type");
var b = new Blob([blob], { type: contentTypeHeader });
downloadLink.href = window.URL.createObjectURL(b);
var fileNamePattern = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
downloadLink.download = fileNamePattern.exec(request.getResponseHeader("content-disposition"))[1];
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
window.URL.revokeObjectURL(b);
}
}
};
request.send();
Code is based on this and this.
FYI, I found that new Blob([response.data], ...) returns almost double the size of response.data when response.data is not returned as blob, but text/plain or application/vnd.openxmlformats-officedocument.spreadsheetml.sheet. To get around it, you need to pass it an array of bytes instead:
var i, l, d, array;
d = this.result;
l = d.length;
array = new Uint8Array(l);
for (var i = 0; i < l; i++){
array[i] = d.charCodeAt(i);
}
var b = new Blob([array], {type: 'application/octet-stream'});
window.location.href = URL.createObjectURL(b);
Code is from here.
Anyways, since the AJAX response is not correct using AngularJS, you won't get a valid xlsx file this way. You need to go with vanilla JS.
How can I encode the data:image/jpeg;base64 data url to be transmitted correctly through an AJAX POST. I have the following code xhr.open('POST', 'http://url-sent-to/image/' + saveImage + '&imageid=' + imageid.value, true); that is doing so now.
However, the URL http://url-sent-to/image/data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD…RRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAH/2Q==&imageid=testimagedata does not look like it will be correct, especially since it has = in it.
$(function () {
var fileInput = document.getElementById("file")
, renderButton = $("#renderButton")
, imgly = new ImglyKit({
container: "#container",
ratio: 1 / 1
});
// As soon as the user selects a file...
fileInput.addEventListener("change", function (event) {
var file;
var fileToBlob = event.target.files[0];
var blob = new Blob([fileToBlob], {"type":fileToBlob.type});
// do stuff with blob
console.log(blob);
// Find the selected file
if(event.target.files) {
file = event.target.files[0];
} else {
file = event.target.value;
}
// Use FileReader to turn the selected
// file into a data url. ImglyKit needs
// a data url or an image
var reader = new FileReader();
reader.onload = (function(file) {
return function (e) {
data = e.target.result;
// Run ImglyKit with the selected file
try {
imgly.run(data);
} catch (e) {
if(e.name == "NoSupportError") {
alert("Your browser does not support canvas.");
} else if(e.name == "InvalidError") {
alert("The given file is not an image");
}
}
};
})(file);
reader.readAsDataURL(file);
});
// As soon as the user clicks the render button...
// Listen for "Render final image" click
renderButton.click(function (event) {
var dataUrl;
imgly.renderToDataURL("image/jpeg", { size: "1200" }, function (err, dataUrl) {
// `dataUrl` now contains a resized rendered image with
// a width of 300 pixels while keeping the ratio
//Convert DataURL to Blob to send over Ajax
function dataURItoBlob(dataUrl) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
var byteString = atob(dataUrl.split(',')[1]);
// separate out the mime component
var mimeString = dataUrl.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a blob, and you're done
//var bb = new BlobBuilder();
//bb.append(ab);
//return bb.getBlob(mimeString);
}
var blob = dataURItoBlob(dataUrl);
var fd = new FormData(document.forms[0]);
var xhr = new XMLHttpRequest();
var saveImage = dataUrl;
//console.log(saveImage);
fd.append("myFile", blob);
xhr.open('POST', 'http://url-sent-to/image/' + saveImage + '&imageid=' + imageid.value, true);
xhr.send(fd);
I have a fiddle setup for an example of what I'm doing. Essentially, the user will select an image, enter a description, and hit render. When you check the Javascript console, you'll see a Blob is created, and the POST message at the bottom: http://jsfiddle.net/mattography/Lgduvce1/2/
You're looking for encodeURI(), which will do exactly what you're looking for.
Note that you're missing a ? to start your querystring.
Also note that making URLs that long is a bad idea; you should send a POST request instead.