Download file from server folder to client pc - javascript

How can you download a file (.mp3) from a publicly accessible folder on the server to the clients pc?
I have tried:
let url = "\\public\\test.mp3";
let xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
var a = document.createElement('a');
// xhr.response is a blob
a.href = window.URL.createObjectURL(xhr.response);
a.download = 'test.mp3';
a.style.display = 'none';
document.body.appendChild(a);
a.click();
};
xhr.open('GET', url);
xhr.send();
But this just downloads the file with 15KB not the entire thing

Just navigate the user to the mp3 file:
window.location.href = '\\public\\test.mp3';

Related

Ajax file download over GET not working in Opera

This code works in all major browsers excpet in latest Opera 71 (Windows).
The behaviour is that no error or info shows up but the download never starts from end user perspective. In developer tools I see the binary content of the example pdf document in response tab.
It seems that the dynamic creation of tags is not working.
function downloadFile(urlToSend) {
var req = new XMLHttpRequest();
req.open("GET", urlToSend, true);
req.responseType = "blob";
req.onload = function (event) {
var URL = window.URL || window.webkitURL;
var contentType = req.getResponseHeader('content-type');
var blob = new Blob([req.response], {type: contentType});
var downloadUrl = URL.createObjectURL(blob);
var contentDisposition = req.getResponseHeader('content-disposition');
//var fileName = req.getResponseHeader("fileName") //if you have the fileName header available
var filename = 'doku.pdf'; //contentDisposition.match(/filename*="(.+)"/)[1];
if (filename) {
// use HTML5 a[download] attribute to specify filename
var a = document.createElement("a");
// safari doesn't support this yet
if (typeof a.download === 'undefined') {
window.location.href = downloadUrl;
} else {
//code which gets executed by Opera
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
window.location.href = downloadUrl;
}
};
req.send();
}

Zip download is not happening

Hi I am new to java script, I am trying to download zip file from a web server running in http://10.1.2.137:5000/download.
When I access the URL alone in the browser as http://10.1.2.137:5000/download, te zip file is getting downloaded , but when I call from java script , the zip file is getting corrupted it seems. Not able to open the zip file with win rar.
Not sure this is the issue with CORS.
$scope.downloadData = function (){
console.log ('Entering in to Download Method')
var url = 'http://10.1.2.137:5000/download';
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.responseType = "arraybuffer";
var linkElement = document.createElement('iframe');
document.body.appendChild(linkElement)
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var blob = new Blob([str2bytes(xhr.response)], {type: "application/zip"});
var fileName = "logs.zip";
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, filename);
} else {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display:none";
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
a.remove();
}
}
}
};
You can use window.open, this will instruct the browser to open the url and start download. e.g.
window.open("http://10.1.2.137:5000/download","_self");

Open FileStreamResult by ajax (as downloaded file)

Is it possible to use an ajax call to open FileStreamResult as a downloaded file?
Controller method
public FileStreamResult DownloadPDF()
{
var stream = myHandler.getFileStream("myfile.pdf");
return File(stream, "application/pdf", "myfile.pdf"));
}
Html code
Click Me
<script type="text/javascript>
$("a.mydownload").click(function () {
$.ajax({
method: 'GET',
url: 'http://myserver/file/DownloadPDF',
success: function (data, status, jqXHR) {
var blob = new Blob([data], { type: "application/pdf" })
var url = window.URL.createObjectURL(blob);
var a = document.createElement("a");
document.body.appendChild(a);
a.href = url;
a.click();
}
});
});
</script>
Running on IE I get access denied, but on Chrome it runs fine. I do however get a "blank"/invalid pdf.
Use XMLHttpRequest() with responseType set to "blob", add download attribute to <a> element
$("a.mydownload").click(function () {
var request = new XMLHttpRequest();
request.responseType = "blob";
request.open("GET", "http://myserver/file/DownloadPDF");
request.onload = function() {
var url = window.URL.createObjectURL(this.response);
var a = document.createElement("a");
document.body.appendChild(a);
a.href = url;
a.download = this.response.name || "download-" + $.now()
a.click();
}
request.send();
});
alternatively, you can use jquery-ajax-blob-arraybuffer.js. See also Add support for HTML5 XHR v2 with responseType set to 'arraybuffer' on $.ajax
Still had issues with IE11, but a minor change to #guest271314 solutions, seems to do the trick.
Set responseType after open.
Use msSaveBlob on IE
$("a.mydownload").click(function() {
var request = new XMLHttpRequest();
request.open("GET", "http://myserver/file/DownloadPDF");
request.responseType = "blob";
request.onload = function() {
var msie = window.navigator.userAgent.indexOf("MSIE");
if (msie > 0) {
window.navigator.msSaveBlob(this.response, "myfile.pdf");
} else {
var url = window.URL.createObjectURL(this.response);
var a = document.createElement("a");
document.body.appendChild(a);
a.href = url;
a.download = this.response.name || "download-" + $.now()
a.click();
}
}
request.send();
});

Download file when clicking on the link in Meteor

I store the mp3 files on my server using https://github.com/CollectionFS/Meteor-CollectionFS. I want to allow user to download the file just by clicking on the link and the 'download' attribute should work fine here i.e.:
download
The problem is that the file is opening/playing in the browser instead of just start to downloading to disk.
As discussed here https://code.google.com/p/chromium/issues/detail?id=373182 I guest it is because of cross origin request, so I tried to follow the suggested solution and use this link
download
with this handler
Template.podcastItemSummary.events({
'click a.btn-download': function(event, instance){
event.preventDefault();
downloadFile($(event.currentTarget).attr('data-url'));
}
});
if (Meteor.isClient) {
downloadFile = function(sUrl){
window.URL = window.URL || window.webkitURL;
var xhr = new XMLHttpRequest();
xhr.open('GET', sUrl, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
var res = xhr.response;
var blob = new Blob([res], {type:"audio/mp3"});
url = window.URL.createObjectURL(blob);
var a = document.createElement("a");
a.style.display = "none";
a.href = url;
a.download = sUrl.split('/').pop();
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
};
xhr.send();
}
}
Now the file is downloaded as expected, but for large files there is a strange delay between 'click' and start of download. Any better solution?
As #ZuzEL wrote, the solution is to just end the link with ?download
download
I stored the url in a separate collection, and now I realized that I should store only the file's id (ubcq5Xev4mkQ3sv5t) as there is a by design solution https://github.com/CollectionFS/Meteor-CollectionFS/wiki/How-to:-Provide-a-download-button
Template.fileList.helpers({
files: function () {
return Files.find();
}
});
and template
<template name="fileList">
<div class="fileList">
{{#each files}}
<div class="file">
<strong>{{this.name}}</strong> Download
</div>
{{/each}}
</div>
</template>
which produces an url that includes a token as well
Download

Downloading mp3 files using html5 blobs in a chrome-extension

I am trying to create a google-chrome-extension that will download an mp3 file. I am trying to use HTML5 blobs and an iframe to trigger a download, but it doesn't seem to be working. Here is my code:
var finalURL = "server1.example.com/u25561664/audio/120774.mp3";
var xhr = new XMLHttpRequest();
xhr.open("GET", finalURL, true);
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
var bb = new (window.BlobBuilder || window.WebKitBlobBuilder)();
bb.append(xhr.responseText);
var blob = bb.getBlob("application/octet-stream");
var saveas = document.createElement("iframe");
saveas.style.display = "none";
saveas.src = window.webkitURL.createObjectURL(blob);
document.body.appendChild(saveas);
delete xhr;
delete blob;
delete bb;
}
}
xhr.send();
When looked in the console, the blob is created correctly, the settings look right:
size: 15312172
type: "application/octet-stream"
However, when I try the link created by the createObjectURL(),
blob:chrome-extension://dkhkkcnjlmfnnmaobedahgcljonancbe/b6c2e829-c811-4239-bd06-8506a67cab04
I get a blank document and a warning saying
Resource interpreted as Document but
transferred with MIME type
application/octet-stream.
How can get my code to download the file correctly?
The below code worked for me in Google chrome 14.0.835.163:
var finalURL = "http://localhost/Music/123a4.mp3";
var xhr = new XMLHttpRequest();
xhr.overrideMimeType("application/octet-stream");
//xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.open("GET", finalURL, true);
xhr.responseType = "arraybuffer";
xhr.onload = function() {
var bb = new (window.BlobBuilder || window.WebKitBlobBuilder)();
var res = xhr.response;
if (res){
var byteArray = new Uint8Array(res);
}
bb.append(byteArray.buffer);
var blob = bb.getBlob("application/octet-stream");
var iframe = document.createElement("iframe");
iframe.style.display = "none";
iframe.src = window.webkitURL.createObjectURL(blob);
document.body.appendChild(iframe);
};
xhr.send(null);
I'm not sure, but i think this is your server's trouble. I've just tried your piece of code to download some sample blob of mp3-file and everything went ok. So maybe:
this file doesn't exist on your server
you server outputs wrong mime type for mp3 files

Categories