Download FIle by Ajax
Download file with AJAX, with two options Open and Download
HTML
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<a href="https://github.com/eligrey/FileSaver.js">FileSaver.js</a> <br>
<button onclick="downloadFile();">Download File</button>
<button onclick="openFile();">Open File</button>
<button onclick="printFile();">Print File</button>
<button onclick="downloadAjax();">Ajax File</button>
JavaScript
function printFile (timeout) {
var blob = new Blob(["Hello, world!"], {type: "application/pdf;charset=utf-8"});
blob = new Blob(newBlob, {type: "text/plain;charset=utf-8"});
timeout = timeout || 2000;
var URL = window.URL || window.webkitURL;
var dataUrl = URL.createObjectURL(blob);
var iFrame = document.createElement('iframe');
iFrame.style.display = 'none';
iFrame.src = dataUrl;
iFrame.onload = function() {
setTimeout(function() {
iFrame.contentWindow.print();
document.body.removeChild(iFrame);
}, timeout);
};
document.body.appendChild(iFrame);
};
function openFile(){
var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
blob = new Blob(newBlob, {type: "text/plain;charset=utf-8"});
//saveAs(blob, "hello world.txt");
// we have to open the window immediately and store the reference
// otherwise popup blockers will stop us
var win = window.open('', '_blank');
try {
var URL = window.URL || window.webkitURL;
var dataUrl = URL.createObjectURL(blob);
win.location = dataUrl;
} catch(e) {
win.close();
return false;
}
}
function downloadAjax (response, status, request) {
/* var disp = request.getResponseHeader('Content-Disposition');
if (disp && disp.search('attachment') != -1) {
var type = request.getResponseHeader('Content-Type');
var blob = new Blob(response, { type : type });
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
window.location = downloadUrl;
} */
$.ajax({
url: "http://localhost:8080/download",
type: "GET", //send it through get method
data: {
gwId: "Walkby2"
},
xhrFields:{
responseType: 'blob'
},
success: function(response, status, request) {
console.warn(response)
var...