IE 9+ Download Attribute workaround - html

I am trying to download a file from my web service. I need to pass complex meta data to the server to know how to download the file. Here is how Im able to accomplish that in evergreen browsers:
// i use angular but not important for this demo
$http.post({ /* complex object */ }).then(xhr){
// use download attribute
// http://davidwalsh.name/download-attribute
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:attachment/csv,' + encodeURI(xhr.data);
hiddenElement.target = '_blank';
hiddenElement.download = $scope.filename + '.csv';
hiddenElement.click();
hiddenElement.remove();
});
of course sense the download attribute is not available on IE I'm not able to post. A workaround I've used before is:
$("body>#download_iFrame").remove();
$("body").append('<iframe name="downloadFrame" id="download_iFrame" style="display:none;" src="" />');
$("#form-download")[0].submit();
and then in html
<form target="downloadFrame"
action="'api/search/export/'"
id="form-download"></form>
problem is I can't pass a object like that. Sure I can put a hidden input and serialize its value but my object is kinda big so that ends up being a problem.
How do you work around this?

If you're only concerned about recent browsers you might take a look at using FileSaver.js. When running on IE10+ it uses navigator.msSaveOrOpenBlob.
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = fuction (eventInfo) {
if (this.status == 200) {
var blob = this.response;
// FileSaver.js usage:
saveAs(blob, "filename.ext");
// Or IE10+ specific:
navigator.msSaveOrOpenBlob(blob, "filename.ext");
}
};
xhr.send();

Related

Changing the pitch of the sound of an HTML5 audio node

I would like to change the pitch of a sound file using the HTML 5 Audio node.
I had a suggestion to use the setVelocity property and I have found this is a function of the Panner Node
I have the following code in which I have tried changing the call parameters, but with no discernible result.
Does anyone have any ideas, please?
I have the folowing code:
var gAudioContext = new AudioContext()
var gAudioBuffer;
var playAudioFile = function (gAudioBuffer) {
var panner = gAudioContext.createPanner();
gAudioContext.listener.dopplerFactor = 1000
source.connect(panner);
panner.setVelocity(0,2000,0);
panner.connect(gainNode);
gainNode.connect(gAudioContext.destination);
gainNode.gain.value = 0.5
source.start(0); // Play sound
};
var loadAudioFile = (function (url) {
var request = new XMLHttpRequest();
request.open('get', 'Sounds/English.wav', true);
request.responseType = 'arraybuffer';
request.onload = function () {
gAudioContext.decodeAudioData(request.response,
function(incomingBuffer) {
playAudioFile(incomingBuffer);
}
);
};
request.send();
}());
I'm trying to achieve something similar and I also failed at using PannerNode.setVelocity().
One working technique I found is by using the following package (example included in the README): https://www.npmjs.com/package/soundbank-pitch-shift
It is also possible with a biquad filter, available natively. See an example here: http://codepen.io/qur2/pen/emVQwW
I didn't find a simple sound to make it obvious (CORS restriction with ajax loading).
You can read more at http://chimera.labs.oreilly.com/books/1234000001552/ch04.html and https://developer.mozilla.org/en-US/docs/Web/API/BiquadFilterNode.
Hope this helps!

Auto Pop Up Save As Window For Firefox

I've been using this code download PDF to directly download a link for pdf but this code only work in Google Chrome
Can someone help me to make this work in Mozilla Firefox and IE8 as well. Because when I try to test it in Mozilla Firefox it opens the links but doesn't pop up the "Save As" window.
I'd use PHP headers so reference the file with something like this for the url:
download PDF
Then use php to deliver the file:
<?php
/* put some validation and injection protection here */
$approvedFiles = ["myFile.pdf","myOtherFile.pdf"];
if (!in_array($_GET['file'],$approvedFiles)){
header("HTTP/1.1 404 Not Found");
die();
}
//otherwise
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="myFile.pdf"');
readfile('myFile.pdf');
Note: pseudo code is not perfect :)
Refs: http://php.net/manual/en/function.header.php
http://jsfiddle.net/RemMp/
<a id="save_data" href="">link</a>
window.URL = window.webkitURL || window.URL;
var a = document.getElementById('save_data');
var data = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg==';
var filename = 'qqq.pdf';
a.download = filename;
a.href = data;
a.textContent = 'Downloading...';
//release memory
a.onclick = function(e){
save_cleanup(this);
};
//force click
document.querySelector('#save_data').click();
function save_cleanup(a){
a.textContent = 'Downloaded';
setTimeout(function(){
a.href = '';
var element = document.getElementById("save_data");
element.parentNode.removeChild(element);
}, 1500);
};

Download attribute on A tag not working in IE

From the following code I'm creating a dynamic anchor tag which downloads a file. This code works well in Chrome but not in IE. How can I get this working
<div id="divContainer">
<h3>Sample title</h3>
</div>
<button onclick="clicker()">Click me</button>
<script type="text/javascript">
function clicker() {
var anchorTag = document.createElement('a');
anchorTag.href = "http://cdn1.dailymirror.lk/media/images/finance.jpg";
anchorTag.download = "download";
anchorTag.click();
var element = document.getElementById('divContainer');
element.appendChild(anchorTag);
}
</script>
Internet Explorer does not presently support the Download attribute on A tags.
See http://caniuse.com/download and http://status.modern.ie/adownloadattribute; the latter indicates that the feature is "Under consideration" for IE12.
In my case, since there's a requirement to support the usage of IE 11 (version 11.0.9600.18665), I ended up using the solution provided by #Henners on his comment:
// IE10+ : (has Blob, but not a[download] or URL)
if (navigator.msSaveBlob) {
return navigator.msSaveBlob(blob, fileName);
}
It's quite simple and practical.
Apparently, this solution was found on the Javascript download function created by dandavis.
Old question, but thought I'd add our solution. Here is the code I used on my last project. It's not perfect, but it passed QA in all browsers and IE9+.
downloadCSV(data,fileName){
var blob = new Blob([data], {type: "text/plain;charset=utf-8;"});
var anchor = angular.element('<a/>');
if (window.navigator.msSaveBlob) { // IE
window.navigator.msSaveOrOpenBlob(blob, fileName)
} else if (navigator.userAgent.search("Firefox") !== -1) { // Firefox
anchor.css({display: 'none'});
angular.element(document.body).append(anchor);
anchor.attr({
href: 'data:attachment/csv;charset=utf-8,' + encodeURIComponent(data),
target: '_blank',
download: fileName
})[0].click();
anchor.remove();
} else { // Chrome
anchor.attr({
href: URL.createObjectURL(blob),
target: '_blank',
download: fileName
})[0].click();
}
}
Using the ms specific API worked best for us in IE. Also note that some browsers require the anchor to actually be in the DOM for the download attribute to work, whereas Chrome, for example, does not. Also, we found some inconsistencies with how Blobs work in various browsers. Some browsers also have an export limit. This allows the largest possible CSV export in each browser afaik.
As of build 10547+, the Microsoft Edge browser is now supporting the download attribute on a tags.
Download Image
Edge features update: https://dev.windows.com/en-us/microsoft-edge/platform/changelog/desktop/10547/
a[download] standard: http://www.w3.org/html/wg/drafts/html/master/links.html#attr-hyperlink-download
This code fragment allows saving blob in the file in IE, Edge and other modern browsers.
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
// Extract filename form response using regex
var filename = "";
var disposition = request.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
}
if (window.navigator.msSaveOrOpenBlob) { // for IE and Edge
window.navigator.msSaveBlob(request.response, filename);
} else {
// for modern browsers
var a = document.createElement('a');
a.href = window.URL.createObjectURL(request.response);
a.download = filename;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
}
}
button.disabled = false;
dragArea.removeAttribute('spinner-visible');
// spinner.style.display = "none";
};
request.open("POST", "download");
request.responseType = 'blob';
request.send(formData);
For IE and Edge use: msSaveBlob
Use my function
It bind your atag to download file in IE
function MS_bindDownload(el) {
if(el === undefined){
throw Error('I need element parameter.');
}
if(el.href === ''){
throw Error('The element has no href value.');
}
var filename = el.getAttribute('download');
if (filename === null || filename === ''){
var tmp = el.href.split('/');
filename = tmp[tmp.length-1];
}
el.addEventListener('click', function (evt) {
evt.preventDefault();
var xhr = new XMLHttpRequest();
xhr.onloadstart = function () {
xhr.responseType = 'blob';
};
xhr.onload = function () {
navigator.msSaveOrOpenBlob(xhr.response, filename);
};
xhr.open("GET", el.href, true);
xhr.send();
})
}
Append child first and then click
Or you can use window.location= 'url' ;
As mentioned in earlier answer , download attribute is not supported in IE . As a work around, you can use iFrames to download the file . Here is a sample code snippet.
function downloadFile(url){
var oIframe = window.document.createElement('iframe');
var $body = jQuery(document.body);
var $oIframe = jQuery(oIframe).attr({
src: url,
style: 'display:none'
});
$body.append($oIframe);
}
I copied the code from here and updated it for ES6 and ESLint and added it to my project.
You can save the code to download.js and use it in your project like this:
import Download from './download'
Download('/somefile.png', 'somefile.png')
Note that it supports dataURLs (from canvas objects), and more... see https://github.com/rndme for details.

Filename of downloaded file in data:Application/octet-stream;

I am trying to download a file using data uri in following manner:
<input type="button"
onclick="window.location.href='data:Application/octet-stream;content-disposition:attachment;filename=file.txt,${details}'"
value="Download"/>
The problem is that the downloaded file is always named 'Unknown', whatever I try to use as
filename. Is this the correct way to give the file a name ? or something else needs to be
done ?
Here's the solution, you just have to add a download attribute to anchor tag
a with desired name
<a href="data:application/csv;charset=utf-8,Col1%2CCol2%2CCol3%0AVal1%2CVal2%2CVal3%0AVal11%2CVal22%2CVal33%0AVal111%2CVal222%2CVal333"
download="somedata.csv">Example</a>
Another solution is to use JQuery/Javascript
Anchor's Download Property
On Safari, you might want to use this, and instruct the user to ⌘-S the file:
window.open('data:text/csv;base64,' + encodeURI($window.btoa(content)));
Otherwise, this uses Filesaver.js, but works ok:
var downloadFile = function downloadFile(content, filename) {
var supportsDownloadAttribute = 'download' in document.createElement('a');
if(supportsDownloadAttribute) {
var link = angular.element('<a/>');
link.attr({
href: 'data:attachment/csv;base64,' + encodeURI($window.btoa(content)),
target: '_blank',
download: filename
})[0].click();
$timeout(function() {
link.remove();
}, 50);
} else if(typeof safari !== 'undefined') {
window.open('data:attachment/csv;charset=utf-8,' + encodeURI(content));
} else {
var blob = new Blob([content], {type: "text/plain;charset=utf-8"});
saveAs(blob, filename);
}
}
Note: There is some AngularJS in the code above, but it should be easy to factor out...
I had the same issue and finally I solved in all browsers serving the CSV file in the server-side:
const result = json2csv({ data });
res.writeHead(200
'Content-Type': 'application/octet-stream',
'Content-Disposition': 'attachment;filename=issues.csv',
'Content-Length': result.length
});
res.end(result);
For those that are using other libraries like angularjs or backbone, you can try something like this.
$('a.download').attr('href', 'data:application/csv;charset=utf-8,'+$scope.data);
For anybody looking for a client-side solution using Javascript only, here is mine, working on any browser except IE 10 and lower (and Edge...why?!):
var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(csv);
var link = document.createElement('a');
link.setAttribute("download", "extract.csv");
link.setAttribute("href", uri);
document.body.appendChild(link);
link.click();
body.removeChild(body.lastChild);

HTML5 FileReader alternative

I need some help with HTML5. I have a script that loops through all the uploaded files and gets each file details. Currently I am using HTML5 techniques that include FileReader. The FileReader function only works in Chrome and Firefox, so I am looking for an alternative which will work in all of the other browsers.
I saw the Stack Overflow question Flash alternative for FileReader HTML 5 API, but I wasn't able to figure how to use this Flash thing, and aren't there any other solutions so I can loop through all of the uploaded files and get each file details (which will work in Safari and Internet Explorer)?
Ended up not using FileReader at all, instead I looped through event.files and got each file by files[i] and sent an AJAX request by XHR with a FormData object (worked for me because I decided I don't need to get the file data):
var xhrPool = {};
var dt = e.dataTransfer;
var files = (e.files || dt.files);
for (var i = 0; i < files.length; i++) {
var file = files[i];
// more code...
xhrPool[i] = getXMLHttpRequest();
xhrPool[i].upload.onprogress = uploadProgress;
initXHRRequest(xhrPool[i], i, file);
data = initFormData(i, file);
xhrPool[i].send(data);
}
function initFormData(uploaded, file) {
var data = new FormData();
data.append(uploaded, file);
// parameters...
return data;
}
function uploadProgress() {
// code..
}
function initXHRRequest(xhr, uploaded, file) {
// code... onreadystatechange...
xhr.open("POST", "ajax/upload.php");
xhr.setRequestHeader("X-File-Name", file.name);
}
function getXMLHttpRequest()
{
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
else {
try {
return new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
catch(ex) {
return null;
}
}
}
Safari was the first one to actually implement the HTML5 file API, and there are several demos. Andrea Giammarchi has a nice description on his blog. There are several frameworks to handle this as well which also have fallbacks for Internet Explorer. Fancyupload is one that comes to mind.